BigDataScholar BigDataScholar - 26 days ago 12
Scala Question

why can't I use TypeTag instead of ClassTag -Scala

I am trying to understand this piece of code

def myFunc[A:ClassTag](seq: A*) = {

println("The array representation is "+ Array[A](seq: _*)) }


I have a couple of questions regarding this :-

  1. Why can't I use TypeTag instead of ClassTag here?

  2. Am I correct in saying that myFunc takes in variable number of some generic types and returns an Array of variable number of generic type ( this doesn't make sense, but why does the code mean that way?)


Answer Source
  1. Because the Array object's apply method specifically requires a ClassTag and not a TypeTag. Here's the documentation. Arrays only need the ClassTag information, and I believe the class predates TypeTag anyway.

  2. Your code does not return the array, it merely prints it. If you changed it to return the array, you could say it takes in a variable number of instances of some generic type (one single type per invocation), and returns an array of elements of that type.