Scala:类型不匹配;找到:所需单位:布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12539777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: type mismatch; found : Unit required: Boolean
提问by Inti
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 并遇到了这个我不明白的错误。我一直在努力解决这个问题并且已经用尽了我的想法。帮助?
scala> def calculate(count: Int) : Boolean =
| if (count<0) false
<console>:8: error: type mismatch;
found : Unit
required: Boolean
if (count<0) false
^
Thanks
谢谢
回答by dhg
You have to have an elseclause, otherwise the type checker doesn't know what the return type is when it's notthe case that count<0.
你必须有一个else条款,否则,类型检查不知道返回类型是什么,当它不是该案件count<0。
def calculate(count: Int): Boolean =
if (count<0) false
else true
Or, better yet, you don't need the if-statement at all:
或者,更好的是,您根本不需要 if 语句:
def calculate(count: Int) = count >= 0

