Skip to content

Instantly share code, notes, and snippets.

@slpsys
Created July 13, 2016 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slpsys/67ec0bba25f4b38bcb87334d538fa286 to your computer and use it in GitHub Desktop.
Save slpsys/67ec0bba25f4b38bcb87334d538fa286 to your computer and use it in GitHub Desktop.
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