Return type in If expression

前端 未结 2 1290
醉话见心
醉话见心 2021-02-12 19:36

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

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 19:41

    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
    

提交回复
热议问题