vendredi 21 juillet 2017

Int Type vs scala.Int Type

I'm using scala reflections to get all fields of a case class that are not methods. I then want to see if the type is a primitive type or string (or an option of these things). Here's a simple working example that checks if a field is a String.

scala> case class SimpleCase(val1: String)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res57: reflect.runtime.universe.Type = String

scala> members.head.typeSignature == typeOf[String]
res58: Boolean = true

Works exactly the way that I would expect it to. Here's where things get weird - when I do the same thing with an Int, or any primitive type for that matter, the type checking test fails. Here's an example of said failure:

scala> case class SimpleCase(val1: Int)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res59: reflect.runtime.universe.Type = scala.Int

scala> members.head.typeSignature == typeOf[Int]
res60: Boolean = false

scala> members.head.typeSignature == typeOf[scala.Int]
res61: Boolean = false

Also, typeOf[Int] prints out

scala> typeOf[Int]
res62: reflect.runtime.universe.Type = Int

The type signature of SimpleCase's val1 states that it is a scala.Int rather than typeOf[Int]'s type signature, which is Int. So I tried comparing val1 to both typeOf[Int] and typeOf[scala.Int] (even though I'm pretty sure they're the same thing) to no avail.

What's going on here? Is there a way around this?





Aucun commentaire:

Enregistrer un commentaire