If 表达式中的返回类型 [英] Return type in If expression

查看:44
本文介绍了If 表达式中的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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
}

Int 作为返回类型 signum (arg: I​​nt): Int

但是

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

AnyVal signum (arg: I​​nt): AnyVal

推荐答案

在没有明确的 else 的情况下,Scala 假定:

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

else ()

其中()Unit 的值.例如,它是 println 返回的值或赋值给 var 的值.

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

这很容易验证:

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

scala> x.isInstanceOf[Unit]
res3: Boolean = true

这篇关于If 表达式中的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆