Return Types in Scala Expressions
In Scala, expressions always returns a value.Some expressions such as if,pattern matching returns value directly and comprehensions like for needs an explicit declaration using yield. So you have to be very clear about the expression you are dealing with.
For instance, if can return non Unit value only when the expression has handled all possible cases. Lets look at an example .
val condition = true
val result: Int = if (condition) 1
types mismatch; found : Unit required: Int
It shows the intuitiveness of Scala compiler. The error comes because else part is missing in the code. Plus we have explicitly mentioned return type as Int. Lets see what if we remove the type.
val condition = true
val result = if (condition) 1
val result: AnyVal
val condition = true
val result = if (condition) 1
val result: AnyVal
val result = if (condition) 1
val result: AnyVal
When we removed the type, compiler error disappeared but result type has become AnyValue. Amazing right ? This is because, In case of false scenario during runtime, the code will return Unit . Lets see it from an example
val codition = false
val result = if (codition) 1
println(result)
println(result.getClass())
Result :
() class scala.runtime.BoxedUnit
Lets keep the return type for a while and fix the compiler error.The error is straight forward.All it needs is else part. So lets not let the compiler to take defensive measure (returning AnyValue) and let us be specific with our needs .
val condition = true
val result: Int = if (condition) 1 else 2
Above code with else part have got rid of compiler errors and would give the expected result.This is a sample why Scala seduces many programmers with its intuitiveness. 😀
Comments
Post a Comment