简体   繁体   English

Scala:类型不匹配; found:需要的单位:布尔值

[英]Scala: type mismatch; found : Unit required: Boolean

Hi I'm just trying out my first bits of scala and have hit this error which I don't understand. 嗨,我只是尝试我的第一部分scala并且遇到了这个我不明白的错误。 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
                 ^

Thanks 谢谢

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 . 你必须有一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM