Tuesday 18 August 2020

Scala: What if condition returns value of some type and else return some other type

 var y = if (x == 10) "Hello World" else 1234.5

Consider the above example, if the value of x is 10, then if expression returns a string, else it returns a real value. In this case, Scala takes the supertype of both String and Double as a type of variable y.

scala> var x = 10
var x: Int = 10

scala> var y = if (x == 10) "Hello World" else 1234.5
var y: Any = Hello World

What if you return the same type of value in both if and else expression blocks?

Scala uses the same type.

scala> var y = if (x == 10) "Hello World" else "Hi!!!!"
var y: String = Hello World

In the above example, both if, else expression blocks return a String value, so the type of variable y is String.

 

What if an expression block does not return anything?

Suppose if the expression block does not return anything, then Scala assigns () to the variable. () is of type Unit which is equivalent to void in Java.

scala> var y = if (x == 11) "Hello World"
var y: Any = ()

scala> println(y)
()

scala> var z = ()
var z: Unit = ()




Previous                                                    Next                                                    Home

No comments:

Post a Comment