import java.util.Random
class Kostka {
val rand = new Random(System.currentTimeMillis())
val value: List[Int] = List(rand.nextInt(6+1))
}
object MyRandom {
def Fill[A](n: Int): List[A] = {
if (n<=0) Nil
else {
var lst = List[A]
for (i <- 1 to n){
lst ++= (new Kostka).value
}
return lst
}
}
}
object Gra {
def main(args: Array[String]): Unit = {
println("Podaj liczbe kosci\n")
val kosci: List[Kostka] = MyRandom.Fill[Kostka](10)
// Policzenie wyniku
println("Strzelaj ile razem wypadło\n")
// przyjecie wyniku
// dopisac ile wypadlo czyli wynik
println("Wypadlo: ")
println(kosci.toString)
}
}
和錯誤:斯卡拉從我想申請方法
a.scala:10: error: missing arguments for method apply in object List;
follow this method with `_' if you want to treat it as a partially applied function
var lst = List[A]
^
one error found
當我有:
var lst = List[A]()
我得到這個錯誤:
a.scala:12: error: type mismatch;
found : List[Any]
required: List[A]
lst ++= (new Kostka).value
^
one error found
如果我使用ListBuffer而不是List,那麼利潤是多少? – matiit 2010-06-27 11:21:19
@matiit:'List'是不可變的。 'ListBuffer'是可變的。選擇最符合您需求的產品。 – 2010-06-27 14:33:43
特別是,在'List'的末尾添加一個元素,就像使用'lst ++ =(new Kostka).value'所做的那樣,代價很高,因爲需要複製'lst'。將一個元素添加到'List'的末尾需要一段時間。 – 2010-06-27 19:10:11