Reputation: 823
I'm struggling to write an anonymous function with by-name parameter. Here is what i tired.
val fun = (x: Boolean, y: =>Int) => if(x) y else 0
This fail with following error.
Error:(106, 31) identifier expected but '=>' found.
val fun = (x: Boolean, y: =>Int) => if(x) y else 0
^
Error:(109, 3) ')' expected but '}' found.
}
^
How ever same code as a standard function works.
def fun1(x: Boolean, y: =>Int) = if(x) y else 0
Any pointers ?
---------------Edit-----------------
I had a two part problem. senia answer solved the initial case. Suppose I have a function takes a function.
def xxx[A,B](f:(A,=>B)=>B)={}
As per senia solution it works.
val fun: (Int, =>Boolean) => Boolean = (x, y) => y
xxx[Int,Boolean](fun)
However I wanna get rid of the intermediate fun and call xxx with anonymous function. Doing
xxx((Int, =>Boolean) => Boolean = (x, y) => y)
Will not work. Any ideas how to do this ?
Upvotes: 10
Views: 2100
Reputation: 38045
You could specify type of anonymous function, instead of types of parameters like this:
val fun: (Boolean, => Int) => Int = (x, y) => if(x) y else 0
scala> fun(false, {println("!"); 2})
res1: Int = 0
scala> fun(true, {println("!"); 2})
!
res2: Int = 2
=> Int
is not a correct type name, it's a special syntax for by-name parameters in parameters block of method declaration or anonymous function type.
See SLS 4.6 Function Declarations and Definitions
ParamType ::= Type
| ‘=>’ Type
| Type ‘*’
In case you don't want to assign anonymous function to variable you could either use type inference like this:
xxx[Int, Boolean]{ (x, y) => y }
Or specify its type this way:
xxx({ (x, y) => y }: ((Int, => Boolean) => Boolean))
Upvotes: 12