2012-05-20 192 views
1

所以我有過這樣的元組的列表:斯卡拉列表類型不匹配

val rooms = List(("Hi", "mom"),("hi", "dad")) 
val foo = rooms.map(arg =>{ 
        var fields = List 
        (new JField("greeting",arg._1), 
         new JField("recipient",arg._2)) 
         new JObject(fields)}) 

了。在土地多的快樂,但是當我改變了房間列表,像這樣:

case class Room(greeting:String, recipient:String) 
val rooms = List(Room("Hi", "mom"),Room("hi", "dad")) 
val foo = rooms.map(arg =>{ 
        var fields = List 
        (new JField("greeting",arg.greeting), 
         new JField("recipient",arg.recipient)) 
         new JObject(fields)}) 

我得到:

[error] <file>: type mismatch; 
[error] found : scala.collection.immutable.List.type (with underlying type object List) 
[error] required: List[blueeyes.json.JsonAST.JValue] 
[error]      new JArray(fields) 

因此,看起來該列表現在是對象而不是以前的JField,爲什麼?

回答

2

,如果你不分離從(List它的工作原理:

var fields = List(
    new JField("greeting", arg.greeting), 
    new JField("recipient", arg.recipient)) 

基本上,它的解析如下:

var fields = List       // assign the List companion object 

(new JField("greeting", arg.greeting), // construct a tuple with two items 
    new JField("recipient", arg.recipient)) // ...but don't use or assign it 

new JObject(fields)      // Make JObject containing the type 

的錯誤出現,因爲JObject構造函數需要一個JValue但你通過它fields其類型List.type

+0

此外,第一個版本也有同樣的問題(至少當我嘗試它)。所以他們之間並沒有什麼區別。 – Owen

+0

@Owen,是的,我也遇到了錯誤。 – dhg

+0

是的,我很愚蠢。我試圖簡化以使問題更清楚。我遇到的問題是我編寫了類似的內容:val a = List(類似於vale a =列表( –