将对象添加到scala中的可变列表中

时间:2014-08-13 12:17:51

标签: scala

我一直在尝试将数据添加到scala中的可变列表中。

我可以添加基本数据类型,感谢Alvin Alexanders excellent blog post使用ListBuffer类,但是当涉及到对象时,我不确定如何继续,所以请不要标记为重复。

import scala.collection.mutable.ListBuffer

var fruits = new ListBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

所以,我试着像这样映射:

import scala.collection.mutable.ListBuffer
var fruits = new ListBuffer[MyClass]()
var d1=new MyClass("data1","data2","data3")

fruits += d1

这会出现以下错误:

type mismatch
found: MyClass
required: MyClass

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

无法重现:

Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

import scala.collection.mutable.ListBuffer
var fruits = new ListBuffer[MyClass]()
class MyClass(a:String, b:String, c:String)
var d1=new MyClass("data1","data2","data3")
fruits += d1

// Exiting paste mode, now interpreting.

import scala.collection.mutable.ListBuffer
fruits: scala.collection.mutable.ListBuffer[MyClass] = ListBuffer(MyClass@291c57ba)
defined class MyClass
d1: MyClass = MyClass@291c57ba
res0: scala.collection.mutable.ListBuffer[MyClass] = ListBuffer(MyClass@291c57ba)

编辑:
您可能已重新定义了MyClass,并导致“类型不匹配”错误。也许是这样的:

scala> :paste
// Entering paste mode (ctrl-D to finish)

import scala.collection.mutable.ListBuffer
class MyClass(a:String, b:String, c:String)
var fruits = new ListBuffer[MyClass]()

// Exiting paste mode, now interpreting.

import scala.collection.mutable.ListBuffer
defined class MyClass
fruits: scala.collection.mutable.ListBuffer[MyClass] = ListBuffer()

scala> :paste
// Entering paste mode (ctrl-D to finish)

class MyClass(a:String, b:String, c:String)
var d1=new MyClass("data1","data2","data3")
fruits += d1

// Exiting paste mode, now interpreting.

<console>:14: error: type mismatch;
 found   : MyClass(in object $iw)(in object $iw)(in object $iw)(in object $iw)
 required: MyClass(in object $iw)(in object $iw)(in object $iw)(in object $iw)
              fruits += d1
                        ^