为什么这个斯卡拉线返回一个单位? [英] Why does this Scala line return a Unit?

查看:99
本文介绍了为什么这个斯卡拉线返回一个单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一些Scala代码来总结从1到9的值,可以被3或5整除。为什么第5行返回一个单位而不是布尔型?

 对象示例{

def main(args:Array [String]){
val answer =(1 until 10).foldLeft(0 )((result,current)=> {
if((current%3 == 0)||(current%5 == 0)){
result + current
}
$)

println(答案)
}

}


解决方案

if表达式有单位类型,因为没有else子句。因此,有时它不返回任何内容(Unit),因此整个表达式的类型为Unit。



(我假设你想问为什么它不返回Int,而不是Boolean) / p>

Here's a bit of Scala code to sum the values from 1 to 9 which are divisible by 3 or 5. Why does line 5 return a Unit and not a Boolean type?

object Sample {

    def main(args : Array[String]) {
        val answer = (1 until 10).foldLeft(0) ((result, current) => {
            if ((current % 3 == 0) || (current % 5 == 0)) {
                result + current
            }
        })

        println(answer)
    }

}

解决方案

The if expression has a type of Unit because there is no else clause. Thus sometimes it returns nothing (Unit) so the entire expression has type Unit.

(I assume you meant to ask why it didn't return Int, not Boolean)

这篇关于为什么这个斯卡拉线返回一个单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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