senthil kumar p senthil kumar p - 1 year ago 72
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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download