Why should we explicitly indicate the class ClassTag?

Now that scala has iterated the erase erase of the JVM type with the class ClassTag, why is it a failure, instead of the compiler always capturing the type signature to verify execution. If there was an implicit parameterized type restriction, it could be called classTag[T]regardless of the declaration of general parameters.

EDIT . I must clarify that I do not mean that scala has to change the signature behind the scenes to always insert ClassTag. Rather, I mean that since it ClassTagshows that scala can capture runtime type information and therefore avoid style-erasure restrictions, why this capture cannot be hidden as part of the compiler, so this information is always available in scala code

My suspicion is that it is backward compatible, compatible with the java ecosystem, binary file size or runtime overhead, but these are just assumptions.

+4
source share
2 answers

Backward compatibility would be completely destroyed, indeed. If you have an easy way:

def foo[A](a: A)(implicit something: SomeType) = ???

, Scala ClassTag . . , foo(a)(someTypeValue), . .

Java . , :

def foo[A : ClassTag](a: A) = ???

ClassTag Scala, Java . ClassTag .

ClassTag<MyClass> tag = scala.reflect.ClassTag$.MODULE$.apply(MyClass.class);
foo(a, tag);

Java 100% , . , , . , , ClassTag, , , .

, , (I, ) . , , ClassTag , , .

, , ClassTag, . , , ClassTag . , , , ClassTag :

def foo[A : ClassTag](a: A): A = a

, . .

val list = List(1, "abc", List(1, 2, 3), List("a", "b"))
def find[A: ClassTag](l: List[Any]): Option[A] =
    l collectFirst { case a: A => a }

scala> find[List[String]]
res2: Option[List[String]] = Some(List(1, 2, 3)) // Not quite! And no warnings, either.

ClassTag , , . . java.lang.String ClassTag. , . ClassTag , getClass. ,

case a if(a.getClass == classOf[String]) => a.asInstanceOf[String]

, , , ClassTag. - find, .

// Can't compile
def find[A](l: List[Any]): Option[A] =
    l collectFirst { case a if(a.getClass == classOf[A]) => a.asInstanceOf[A] }

, - ClassTag, ? a.classTag == classTag[A], A . ClassTag .

+3

, - , (, ). " " Scala Java. , , , .

+2

All Articles