• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scala functions

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How could I use the following function?

def func = { x: Int => Int }

When I call func, I get a reference to a function that takes an Int and returns an Int. How do I make use of that function reference, pass a function that simply multiplies the input parameter?
 
Sresh Rangi
Ranch Hand
Posts: 52
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
func doesn't return an Int; it literally returns Int. It ignores the parameter and returns the same thing every time:



A function that returns an Int can be written as:



and a function that takes such a function as a parameter can be written as:

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that!

I'm trying to get my head around another one!



contents is a parameter-less function. How does contents(0) does not throw an error?
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it like this in Java?



Is it a feature of the parameter-less methods in Scala that I can use the return values inside the parenthesis?
 
Sresh Rangi
Ranch Hand
Posts: 52
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's the same as "contents()[0]" in Java. The method can't be called with any parameters so the parenthesis aren't used for arguments. Contents is called first, and then the parenthesis access the returned array by index:



This is different from a method with an empty parameter list which can be called with or without parenthesis:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic