簡體   English   中英

將對象添加到Scala中的可變列表

[英]Add objects to a mutable list in scala

我一直在嘗試將數據添加到Scala中的可變列表中。

由於Alvin Alexanders出色的博客文章使用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

有人能幫我一下嗎?

無法復制:

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
                        ^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM