senthil kumar p senthil kumar p - 1 month ago 6x
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


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:

    val b = 10 + 20
    b // return b, which is an Int
> 30