Return type in If expression

前端 未结 2 1291
醉话见心
醉话见心 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:51

    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.

提交回复
热议问题