2017-03-16 166 views
1

这里是我的代码从列表斯卡拉测试意外的错误,“)”预期,但“}”发现

object kp { 
    def main(args: Array[String]) { 

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

val a = 1 :: 4 :: 5 :: -4:: Nil 
println(max(a)) 

} 
} 

当我想测试我的示例文件夹中的代码与SBT找到最大

[info] Compiling 1 Scala source to /home/milenko/example/target/scala-2.11/classes... 
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:138: ')' expected but '}' found. 
[error] } 
[error] ^
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:148: ')' expected but '}' found. 
[error] } 
[error] ^
[error] two errors found 

错误指

test("maximum with one negative number") { 
    assert(max(List(1,4,5,-4)) === 5) 
    } 

test("maximum with some repeated elements"){ 
    assert(max(List(2,2,2,2)) === 2) 
    } 

我没有线索,为什么这happens.Here是整个文件

http://www.filedropper.com/listssuite

现在我已经删除了该文件的一些测试,它只有135 lines.But我得到了相同的

wc -l ListsSuite.scala 
135 ListsSuite.scala 
[email protected]:~/example/src/test/scala/example$ cd ~/example 
[email protected]:~/example$ sbt 
[info] Loading global plugins from /home/milenko/.sbt/0.13/plugins 
[info] Loading project definition from /home/milenko/example/project 
[info] Set current project to progfun1-example (in build file:/home/milenko/example/) 
> test 
[info] Compiling 1 Scala source to /home/milenko/example/target/scala-2.11/classes... 
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:138: ')' expected but '}' found. 
[error] } 
[error] ^
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:148: ')' expected but '}' found. 
[error] } 
[error] ^
[error] two errors found 
[error] (compile:compileIncremental) Compilation failed 
[error] Total time: 1 s, completed 16/03/2017 13:43:43 

非常奇怪,做什么:138和:148表示什么?

+0

看起来像ListsSuite.scala中的语法错误,可能在报告的位置之前。你可以添加完整的文件吗? – Harald

+0

请提供更多详情。如果你想,我有一个小例子来检查你的函数'max'。并没有什么建议,你不需要引发异常,你的功能不纯粹是功能性的,因为有副作用。 – alifirat

+0

它编译和运行我sbt – FatTail

回答

0

我在filedropper链接中看不到任何东西(可能它已过期?),但我知道导致类似编译器错误的一个错误是尾随逗号。我不认为这是你的问题,但了解编译器正在做什么可能对你的情况有所帮助。

这是一个简单的文件Comma.scala

val map = Map(
    1 -> "one", 
    2 -> "two", // <--- comma after last argument 
) 

尝试使用Scala 2.11编译这给:

$ scala Comma.scala 
Comma.scala:4: error: illegal start of simple expression 
) 
^ 
Comma.scala:4: error: ')' expected but eof found. 
) 
^ 
two errors found 

第二个错误是喜欢你的一个。

我的猜测是:

  • "illegal start of simple expression"是因为它是最后一个逗号后期待一个表达式(如3 -> "three"),但它遇到右括号,而不是它认为到不是一个有效的表达
  • 因为前面的括号在解析参数到Map(..)时被消耗了,当编译器完成处理参数时,它会上升到一个级别以找到关于Map(的关闭')',但是命中了其他东西(在我的情况下,文件结束和在你的情况下,来自封闭区的'}'代码的ck。这会产生错误')' expected but ... found

这第二个错误相匹配的一个,以便它可以指向出乱子在那里的解析你的论点,吃你的右括号。这个信息本身就是一个红色的鲱鱼,因为当真正的问题可能更早的时候,它指向了结束括号。

如果你是一个用来拖拽括号的python开发人员,这可能会导致很多头部划伤!

我有一个情况,scala 2.12编译器实际上可以处理尾随逗号,但不幸的是我不能用适合SO的小例子来重现它。不幸的是,这种细微差异可能会在2之间创建非向后兼容的代码。12和以前的版本。