简体   繁体   English

为什么我不能使用TypeTag而不是ClassTag -Scala

[英]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? 为什么我不能在这里使用TypeTag而不是ClassTag?
  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?) 我是否正确地说myFunc接受了一些泛型类型的变量号并返回了一个泛型类型的变量号数组(这没有意义,但是为什么代码如此表示?)

Thanks 谢谢

  1. Because the Array object's apply method specifically requires a ClassTag and not a TypeTag . 因为Array对象的apply方法专门需要ClassTag而不是TypeTag Here's the documentation . 这是文档 Arrays only need the ClassTag information, and I believe the class predates TypeTag anyway. 数组只需要ClassTag信息,而且我相信该类早于TypeTag

  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. 如果将其更改为返回数组,则可以说它接收了一定数量的某种通用类型的实例(每次调用一个单一类型),并返回该类型的元素的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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