简体   繁体   English

Scala类型不匹配;找到:布尔值必需:List [Int]

[英]Scala type mismatch;found : Boolean required: List[Int]

I have tried to resolve my sbt testing with simple example 我试图用一个简单的例子解决我的sbt测试

package example
object Lists {
    def sum(xs: List[Int]): Int = {

        xs match {
      case x :: tail => x + sum(tail)
      case Nil => 0
     }
    }
    def max(xs: List[Int]): Int = {
      xs match {
        case Nil => throw new java.util.NoSuchElementException()
        case List(x) => x
        case x :: y :: rest => max ((if (x > y) x else y) :: rest)  
    }
    }

  }

The second file can be downloaded from http://www.filedropper.com/listssuite_1 可以从http://www.filedropper.com/listssuite_1下载第二个文件

When I try test with sbt 当我尝试用sbt测试

[error] /home/milenko/dom1/example/src/test/scala/example/ListsSuite.scala:122: type mismatch;
[error]  found   : Boolean
[error]  required: List[Int]
[error]     assert(sum(List() === 0))
[error]                       ^
[error] /home/milenko/dom1/example/src/test/scala/example/ListsSuite.scala:134: type mismatch;
[error]  found   : Boolean
[error]  required: List[Int]
[error]       assert(max(List(1, -4, 2, 6) === 6))
[error]                                    ^
[error] two errors found
[error] (test:compileIncremental) Compilation failed
[error] Total time: 1 s, completed 17/03/2017 10:43:00

I do not understand why this happens.How it comes that compiler found my type as Boolean? 我不明白为什么会这样,编译器怎么发现我的类型是布尔值?

This is faulty: 这是错误的:

assert(sum(List() === 0))

because the type of the parameter of sum is boolean ( List() === 0 ) 因为sum参数的类型是boolean( List() === 0

Try: assert(sum(List()) === 0) instead. 试试: assert(sum(List()) === 0)

Same goes for the max function. max函数也是如此。

List() === 0 is an Expression of type Boolean because it could be either true (if the empty list is equal to the number zero) or false. List() === 0是布尔类型的表达式,因为它可以为true(如果空列表等于数字零)或false。 Or more accurately it can only ever be false because the empty list is never equal to 0. You then try to calculate the sum of that Boolean, which is a type error. 或更准确地说,它只能是假的,因为空列表永远不会等于0。然后,您尝试计算该布尔值的总和,这是类型错误。

The same goes for line 134. 134行也是如此。

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

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