I am new to scala. I don't understand the compilation error for the below code:
def delayed( t:(Int)=> Int):Unit={
println("In delayed method")
var y=t;
println(y)
}
def time(x:Int):Int={
x*2
}
and when I call
delayed(time(8))
I get the following error:
scala> delayed(time(8))
<console>:15: error: type mismatch;
found : Int
required: Int => Int
delayed(time(8))
^
Please explain what is the issue? Please also suggest a good link to understand functions and function literals in scala. I am not able to understand fully.
Thanks so much
Edit:
Please tell the difference between
def delayed( t: Int => Int):Unit = {
and
def delayed(t: =>Int):Unit {
and
def delayed(t:=>Int):Unit { (without space b/w ":" and "=>"))
Your function
delayedexpects function as an argument, however, you passedInt. That's why you get the error.The type of the argument of
delayedisInt=>Int, which means it is a function accept oneIntas an argument and returnsInt.Your function
timeisInt=>Intfunction, however, when you passtime(8)to thedelayedfunction,time(8)will be evaluated before it is passed todelay, and the evaluation result is just anInt.If you pass the
timefunction only, it will work.If you want to pass
time(8)as a function argument, you should changetimefunction to return function:You also need to modify
delayedfunction like the below:Then you can pass
time(8)todelayed.Or you can use call by name as @Tzach mentioned in the comment.