简体   繁体   中英

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: _*))  }

myFunc(Seq(1,2),Seq(3,4,5,6))
myFunc("a","b","c")

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?)

Thanks

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM