Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display all types of an object (in Scala)?

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 ?) ?

like image 713
John Threepwood Avatar asked Jun 28 '12 16:06

John Threepwood


People also ask

What is the type of an object in Scala?

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.

How do you find the type of a variable in Scala?

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.

Which is the supertype of all types that refer to objects in Scala?

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 .

What are the types in Scala?

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.


2 Answers

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.

like image 103
Travis Brown Avatar answered Oct 20 '22 18:10

Travis Brown


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
like image 44
Daniel C. Sobral Avatar answered Oct 20 '22 16:10

Daniel C. Sobral