Scala expression evaluation

functional-programming, scala

Solution

What is the difference between a function that return evaluate to an Int and the expression 2 + 2.

A function that evaluates to an Int might have side effects

var a = 0
def fn: Int = {
  a = a + 1
  1
}

Every call to fn changes the value of a.

Then why on earth, the compiler does not complain that a function that is suppose to evaluate to Unit, gets a body that evaluate to another type, as it would happens between other types.

When you specify Unit as the return type the compiler does an implicit conversion from whatever value the function returns to Unit (there is only one Unit value as it is an object, you can think of it as the void type of Scala).

Problem

I'm intrigued by the following Scala compiler behavior. When i declare a function of type unit, but nevertheless provide as body a function that evaluate to an Int, the Scala compiler is ok with it. ``` def add(x:Int, y:Int) = x + y def main(args: Array[String]): Unit = {add(args(0).toInt, args(0).toInt)} ``` While the same is not true with other type such in ``` def afunc: String = {1} //type mismatch; found : Int(1) required: String ``` Also if i write ``` def afunc: Unit = {1} ``` or ``` def main(args: Array[String]): Unit = {2 + 2} // Which is just like the first addition above ``` In both case i get the following warning: ``` a pure expression does nothing in statement position; you may be omitting necessary parentheses ``` In a sense there is 2 questions here. What is the difference between a function that return evaluate to an Int and the expression 2 + 2. Then why on earth, the compiler does not complain that a function that is suppose to evaluate to Unit, gets a body that evaluate to another type, as it would happens between other types. Many thanks in advance, Maatari

Original source