Scala:类型不匹配;找到:所需单位:布尔值 [英] Scala: type mismatch; found : Unit required: Boolean
本文介绍了Scala:类型不匹配;找到:所需单位:布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是在尝试我的第一批 Scala 并且遇到了这个我不明白的错误.我一直在努力解决这个问题并且已经用尽了我的想法.帮助?
Hi I'm just trying out my first bits of scala and have hit this error which I don't understand. I've been trying to work it out and have exhausted my ideas. Help?
scala> def calculate(count: Int) : Boolean =
| if (count<0) false
<console>:8: error: type mismatch;
found : Unit
required: Boolean
if (count<0) false
^
谢谢
推荐答案
你必须有一个 else
子句,否则类型检查器不知道返回类型是什么 不是 count<0
的情况.
You have to have an else
clause, otherwise the type checker doesn't know what the return type is when it's not the case that count<0
.
def calculate(count: Int): Boolean =
if (count<0) false
else true
或者,更好的是,您根本不需要 if 语句:
Or, better yet, you don't need the if-statement at all:
def calculate(count: Int) = count >= 0
这篇关于Scala:类型不匹配;找到:所需单位:布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文