senthil kumar p senthil kumar p - 3 months ago 11
Scala Question

Getting an error while passing an expression asa fucntion parameter

scala> def sum(a:Int)={a} //I have defined the function with a single parameter
sum: (a: Int)Int

sum{val b=10+20} //passing the parameter as expression block

Getting error

scala> sum{val b=10+20}
<console>:9: error: type mismatch;
found : Unit
required: Int
sum{val b=10+20}


Why is it expecting
Unit
here?

Answer

The error is that {val b = 10 + 20} is of type Unit while sum is expecting an Int.

You can either call sum directly without assigning the variable:

sum(10 + 20)
> 30

Or make the block return an Int, like:

sum{
    val b = 10 + 20
    b // return b, which is an Int
}
> 30
Comments