scala列表类型不匹配

时间:2012-05-20 21:51:36

标签: list scala type-inference

所以我有这样的元组列表:

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)

所以看来这个列表现在是Object而不是之前的JField,为什么会这样?

1 个答案:

答案 0 :(得分: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