Skip to content

Instantly share code, notes, and snippets.

@freakhill
Last active December 22, 2015 12:38
Show Gist options
  • Save freakhill/6473407 to your computer and use it in GitHub Desktop.
Save freakhill/6473407 to your computer and use it in GitHub Desktop.
Compare static TypeTag to runtime Class
import scala.reflect.runtime.universe._
class A[E](e:E)(implicit t: TypeTag[E]){
def c(o:Any) = {
val TypeRef(_, klass_symbol, _) = t.tpe
println(s"ClassSymbol extracted from TypeTag[E] '${klass_symbol.asClass}' : ClassSymbol")
println(s"Class extracted from o:Any parameter = '${o.getClass}' : Class[??]")
runtimeMirror(getClass.getClassLoader).runtimeClass(klass_symbol.asClass) == o.getClass
}
}
(new A(1)) c 2 // fails! Int and java.lang.Integer
(new A("a") "b") // succeeds!
/* -- My understanding --
difference between types and classes:
they are closely related BUT:
Multiple classes (accessible through different class loaders) can implement the same Type.
A "Type" is a set of valid objects, possibly defined by some constraints.
A "Class" (defined through the help of type annotations) is AN implementation of a Type,
but different classes (accessible through different classloaders in the JVM world) can implement
different behaviours. Thus we can have different classes matching the same type.
Why doesn't this work then:
class A {}
class B {}
typeOf[A] =:= typeOf[B] // <- false
Well it seems that the name of the class is an element of it's type (at least for JVM/Scala).
*/
// nice thing i can do now
class CompareThing[E : TypeTag](val o : E) {
def test(that : E) : Boolean = {
println("yay!") // just something, anything
true
}
override def equals(that: Any): Boolean = {
def klass(s: Symbol) = runtimeMirror(getClass.getClassLoader).runtimeClass(s.asClass)
typeOf[E] match {
case TypeRef(_, symbol, _) if klass(symbol) == that.getClass => test(that.asInstanceOf[E])
case _ => false
}
}
}
(new CompareThing("a")) == 2 // returns false
(new CompareThing("a")) == "b" // returns true!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment