1

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
  }

2 Answers 2

5

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> 
Sign up to request clarification or add additional context in comments.

Comments

1

You're looking for Array#clone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.