Created
July 13, 2016 17:10
-
-
Save slpsys/67ec0bba25f4b38bcb87334d538fa286 to your computer and use it in GitHub Desktop.
Wrangling the type system _and_ getting runtime type info
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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