在Scala中,如何在运行时将类型参数传递给Seq []

时间:2016-11-29 10:11:26

标签: scala type-parameter

我想将类型参数传递给Scala集合,如Seq,Array等。

例如,

 val a: Seq[Int];       // it's easy to specify a type parameter "Int"

 val b: Seq[xxxxxxx];   // I want to receive a type of Seq from other like functions parameters or any other variables in runtime.

是否可以在Scala中使用?

其实我想这样做......

def fun( arr1 : Any, arr2 : Any, arr3: Any ) {
   val seq: Seq[???] = Seq(arr1, arr2, arr3); 
   myOwnLibrary(seq); // Seq[Any] is not available as a myOwnLibrary's parameter; 
}

1 个答案:

答案 0 :(得分:2)

不确定,但这可能是你想要做的:

scala> def mkArray[T : ClassTag](elems: T*) = Array[T](elems: _*)
mkArray: [T](elems: T*)(implicit evidence$1: scala.reflect.ClassTag[T])Array[T]

scala> mkArray(42, 13)
res0: Array[Int] = Array(42, 13)

scala> mkArray("Japan","Brazil","Germany")
res1: Array[String] = Array(Japan, Brazil, Germany)

http://www.scala-lang.org/api/current/scala/reflect/ClassTag.html