Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type in If expression

Tags:

scala

I am learning scala and can't understand why:

def signum(arg: Int) = {
    if(arg > 0 ) 1
    else if(arg < 0) -1
    else 0
}

Has Int as return type signum (arg: Int): Int

But

def signum(arg: Int) = {
    if(arg > 0 ) 1
    else if(arg < 0) -1
    else if(arg == 0) 0
}

Has AnyVal signum (arg: Int): AnyVal

like image 885
ggenikus Avatar asked Feb 07 '12 12:02

ggenikus


People also ask

What is the return type of IF statement?

if (cond) { expr } returns common base type of Unit and type of expr , just like if (cond) { expr } else { () } . Show activity on this post. As always, an if statement evaluates a logical condition and has to return a logical result.

Can I use return in if statement?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number. If the value is omitted, undefined is returned instead.

What is the return value of IF statement?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")


2 Answers

It happens because in the second case you have not specified final else part. In this case the return type of this missing branch would be Unit. So Scala compiler infers AnyVal as a common parent of Int and Unit.

you can try to add explicit return type to the function signature:

def signum(arg: Int): Int = ...

It will not compile with following error:

 found   : Unit
 required: Int
    else if(arg == 0) 0
         ^
one error found

So the compiler tells you that result type of the last if is actually Unit and not Int.

like image 105
tenshi Avatar answered Sep 25 '22 14:09

tenshi


In the absence of an explicit else, Scala assumes this:

else ()

Where () is the value of Unit. It's the value returned by println or assignment to var, for example.

This can be easily verified:

scala> val x = if (false) 1
x: AnyVal = ()

scala> x.isInstanceOf[Unit]
res3: Boolean = true
like image 36
Daniel C. Sobral Avatar answered Sep 25 '22 14:09

Daniel C. Sobral