With the isInstanceOf
method, one can check the type of an object. For example:
scala> val i: Int = 5
i: Int = 5
scala> val a: Any = i
a: Any = 5
scala> a.isInstanceOf[Any]
res0: Boolean = true
scala> a.isInstanceOf[Int]
res1: Boolean = true
scala> a.isInstanceOf[String]
res2: Boolean = false
How can one display all types of an object (if it is possible at all ?) ?
Scala is more object-oriented than Java because in Scala, we cannot have static members. Instead, Scala has singleton objects. A singleton is a class that can have only one instance, i.e., Object. You create singleton using the keyword object instead of class keyword.
Use the getClass Method in Scala The getClass method in Scala is used to get the class of the Scala object. We can use this method to get the type of a variable. The output above shows that it prints java. lang.
Scala Type Hierarchy Any is the supertype of all types, also called the top type. It defines certain universal methods such as equals , hashCode , and toString .
There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Scala has both numeric (e.g., Int and Double) and non-numeric types (e.g., String) that can be used to define values and variables.
You can do this pretty easily in 2.10 (M4 or later):
import scala.reflect.runtime.universe._
def superTypes(t: Type): Set[Type] =
(t.parents ++ t.parents.flatMap(superTypes)).toSet
def allTypes[A](a: A)(implicit tag: TypeTag[A]) = superTypes(tag.tpe) + tag.tpe
Which gives us the following:
scala> allTypes(1).foreach(println)
AnyVal
Any
NotNull
Int
scala> allTypes("1").foreach(println)
String
Any
Object
Comparable[String]
CharSequence
java.io.Serializable
scala> allTypes(List("1")).foreach(println)
scala.collection.LinearSeq[String]
scala.collection.GenSeq[String]
scala.collection.IterableLike[String,List[String]]
scala.collection.GenIterable[String]
scala.collection.GenTraversableLike[String,Iterable[String]]
...
You'll have a much harder time trying to do anything like this pre-2.10.
Here's another solution, which makes use of the baseType
method to reify the type parameter.
import scala.reflect.runtime.universe._
def typesOf[T : TypeTag](v: T): List[Type] =
typeOf[T].baseClasses.map(typeOf[T].baseType)
Example:
scala> typesOf("1") foreach println
String
CharSequence
Comparable[String]
java.io.Serializable
Object
Any
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With