How to display all types of objects (in Scala)?

Using the isInstanceOf method, isInstanceOf can check the type of an object. For instance:

 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 to display all types of objects (if possible at all?)?

+6
source share
2 answers

You can do this quite 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 will have a much harder time to do something like this pre-2.10.

+6
source

Here's another solution using the baseType method to validate 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 
+1
source

Source: https://habr.com/ru/post/919261/


All Articles