Reputation: 369
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 "=>"))
Upvotes: 1
Views: 1935
Reputation: 29448
Your function delayed
expects function as an argument, however, you passed Int
. That's why you get the error.
The type of the argument of delayed
is Int=>Int
, which means it is a function accept one Int
as an argument and returns Int
.
Your function time
is Int=>Int
function, however, when you pass time(8)
to the delayed
function, time(8)
will be evaluated before it is passed to delay
, and the evaluation result is just an Int
.
scala> delayed(time(8))
<console>:14: error: type mismatch;
found : Int
required: Int => Int
delayed(time(8))
^
If you pass the time
function only, it will work.
scala> delayed(time)
In delayed method
<function1>
If you want to pass time(8)
as a function argument, you should change time
function to return function:
scala> def time(x:Int) = () => x*2
You also need to modify delayed
function like the below:
def delayed(t:()=>Int) {
println("In delayed method")
var y=t();
println(y)
}
Then you can pass time(8)
to delayed
.
scala> delayed(time(8))
In delayed method
16
Or you can use call by name as @Tzach mentioned in the comment.
scala> def delayed(t: =>Int) {
| println("In delayed method")
| var y = t
| println(y)
| }
delayed: (t: => Int)Unit
scala> def time(t:Int) = t*2
time: (t: Int)Int
scala> delayed(time(8))
In delayed method
16
Upvotes: 2
Reputation: 5700
Method delayed
expects a function with Input param Int
and return type Int
But in your example you are passing result of time
function.
This will solve your issue.
delayed(time)
Upvotes: 1