Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrangling the type system _and_ getting runtime type info
import scala.reflect.runtime.{universe => ru}
// Trivial class hierarchy
class NotionalObject
class Car extends NotionalObject
class Dog extends NotionalObject
// Not part of the hierarchy
class AbstractExpressionism
// Needs to be a `NotionalObject` *and* we want runtime type info (e.g. type tag)
def factoryConsumer[T <: NotionalObject : ru.TypeTag](a: () => T) = {
// Getting the type of T at runtime via: http://www.scala-lang.org/api/current/scala-reflect/index.html#scala.reflect.api.TypeTags$TypeTag
println(ru.typeTag[T].tpe)
a()
}
scala> factoryConsumer(() => new Dog)
Dog
res0: Dog = Dog@47a86fbb
scala> factoryConsumer(() => new Car)
Car
res1: Car = Car@346939bf
// Won't work, because we're specifying type constraints (T <: NotionalObject)
scala> factoryConsumer(() => new AbstractExpressionism)
<console>:12: error: inferred type arguments [AbstractExpressionism] do not conform to method factoryConsumer's type parameter bounds [T <: NotionalObject]
factoryConsumer(() => new AbstractExpressionism)
^
<console>:12: error: type mismatch;
found : () => AbstractExpressionism
required: () => T
factoryConsumer(() => new AbstractExpressionism)
^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.