worldterminator
worldterminator

Reputation: 3066

Convert Array[AnyVal] to primitive Array[T], T can be Int, Double and etc in scala

I learnt that in scala Array is not a convariant collection. If I have an array of AnyVal, and all elements in array has the same type, how can I make it an array of primitives?

I am think to use the first element of the array like to detect the data type. Like the code below:

def convert(arr:Array[AnyVal]):Array[_] = {
  val firstElement = arr.head
  firstElement match {
    case y:Int => ???
    case y:Long => ???
    case y:Float => ???
    case y:Double => ???
     ... 
  }
}

Upvotes: 0

Views: 275

Answers (2)

beria
beria

Reputation: 193

I am not sure if this is an optimal solution (or for that matter the idea of taking AnyVals input, and converting them to primitives). But typecasting all elements to the desired type should work. Here is a snippet I just tried out.

  def convert(ar: Array[AnyVal]): Array[_] = {
    ar.head match {
      case y: Int => ar.map(_.asInstanceOf[Int])
      case y: Long => ar.map(_.asInstanceOf[Long])
      case _ => Array() // do check if this can be the case
    }
  }

Upvotes: 0

Tim
Tim

Reputation: 27421

The return type of a function is defined at compile time. You can't change the return type of a function based on data that is passed to the function.

The type of a value is also defined at compile time at the point where it is created. However that value can be held in a variable of any supertype of the value type, which is what makes the type system so powerful. Scala also makes it easy to tell the actual type of a value by using pattern matching.

If you know the type you want at compile time, use collect to narrow the type of a value using pattern matching. For example, to get an list of Double from a list of AnyVal do this:

val doubles: List[Double] = anyList.collect{ case d: Double => d }

Any non-Double values will be discarded.

Also note that Array is a Java hang-over, so prefer Scala types like List or Vector.

Upvotes: 1

Related Questions