当前位置: 动力学知识库 > 问答 > 编程问答 >

Initializing anytype Array in Scala

问题描述:

How can I initialize array with type A to have same length as other array? (in this case A is either String or Int)

 def init_arr_with_same_len[A](arr1: Array[A]): Array[A] = {

val len = arr1.length

val arr2 = new Array[A](len)

arr2

}

网友答案:

Arrays are something a little bit special when compared to other collection types. See this lovely article for more details (http://docs.scala-lang.org/overviews/collections/arrays.html).

The short of it is in order for Arrays in scala to support generics (which java arrays do not), you need to provide a scala.reflect.ClassTag for the generic type.

Welcome to Scala version 2.11.7 (OpenJDK 64-Bit Server VM, Java 1.8.0_65).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.reflect.ClassTag
import scala.reflect.ClassTag

scala> def arrayOfSameTypeAndSize[A](a: Array[A])(implicit ct: ClassTag[A]): Array[A] = new Array(a.size)
arrayOfSameTypeAndSize: [A](a: Array[A])(implicit ct: scala.reflect.ClassTag[A])Array[A]

scala> val x: Array[Int] = arrayOfSameTypeAndSize(Array(1,2,3))
x: Array[Int] = Array(0, 0, 0)

scala>

Or slightly more succinctly.

scala> def arrayOfSameTypeAndSize[A: ClassTag](a: Array[A]): Array[A] = new Array(a.size)
arrayOfSameTypeAndSize: [A](a: Array[A])(implicit evidence$1: scala.reflect.ClassTag[A])Array[A]

scala> val x: Array[Int] = arrayOfSameTypeAndSize(Array(1,2,3))
x: Array[Int] = Array(0, 0, 0)

scala> 
网友答案:

You're looking for Array#clone.

分享给朋友:
您可能感兴趣的文章:
随机阅读: