2012-11-03 75 views

回答

32

這被稱爲可變數量的參數或簡短可變參數。它的靜態類型是Seq[T],其中T代表T*。因爲Seq[T]是一個接口,所以它不能用作實現,在這種情況下是scala.collection.mutable.WrappedArray[T]。爲了找出這樣的事情可能是有用使用REPL:

// static type 
scala> def test(args: String*) = args 
test: (args: String*)Seq[String] 

// runtime type 
scala> def test(args: String*) = args.getClass.getName 
test: (args: String*)String 

scala> test("") 
res2: String = scala.collection.mutable.WrappedArray$ofRef 

可變參數通常在組合與_*符號,這是一個提示編譯器將Seq[T]的元素傳遞給函數,而不是使用

scala> def test[T](seq: T*) = seq 
test: [T](seq: T*)Seq[T] 

// result contains the sequence 
scala> test(Seq(1,2,3)) 
res3: Seq[Seq[Int]] = WrappedArray(List(1, 2, 3)) 

// result contains elements of the sequence 
scala> test(Seq(1,2,3): _*) 
res4: Seq[Int] = List(1, 2, 3) 
+1

是的,這有和有趣的效果,你不能馬上通過VAR-LEN ARGS,'高清F1中的序列本身(參數爲:int *)= args.length; def f2(args:Int *)= f1(args)'。它將在f2定義中給出'找到Seq [Int],而Int需要不匹配錯誤'。爲了規避,你需要'def f2 = f1(args:_ *)'。所以,編譯器認爲這個參數是一個單一的值,並且在編譯時相同的順序:) – Val

相關問題