2017-03-16 167 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和以前的版本。