相关疑难解决方法(0)

Scala单位类型

我使用opencsv来解析csv文件,我的代码是

while( (line = reader.readNext()) != null ) { .... }
Run Code Online (Sandbox Code Playgroud)

我收到编译器警告说:

 comparing values of types Unit and Null using `!=' will always yield true
 [warn]     while( (aLine = reader.readNext()) != null ) {
Run Code Online (Sandbox Code Playgroud)

我应该怎么做while循环?

scala while-loop

31
推荐指数
4
解决办法
2万
查看次数

无限循环似乎混淆了Scala的类型系统

这是一个人工玩具示例,演示了我的问题:

def sscce(): Int = {
  val rand = new Random()
  var count = 0
  while (true) {   // type mismatch; found: Unit, required: Int
    count += 1
    if (rand.nextInt() == 42) return count
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能帮助编译器理解这个方法总会返回一个Int

我知道上面的玩具示例很容易被重构以完全摆脱无限循环,但我真的希望在我的实际代码中有无限循环.相信我;)

scala type-inference return-type infinite-loop

2
推荐指数
1
解决办法
131
查看次数