Reputation: 25
I want to get the name of a class passed as a parameter to a function using shapeless. I've tried this:
def sayMyName[T](t: T): String = Typeable[T].describe // error: class type required but T found
If T
is replaced with a concrete type, there's no problem. Is it possible to make something like this work using shapeless?
Upvotes: 1
Views: 107
Reputation: 22595
You just need to add Typeable
typeclass as context bound of your type T
:
def sayMyName[T: Typeable](t: T): String = Typeable[T].describe
sayMyName("") //String
You could also explicitly declare implicit parameter:
def sayMyName[T](t: T)(implicit typeable: Typeable[T]): String = Typeable[T].describe
By adding context bound you're asking the compiler to wait with resolving Typeable
typeclass until sayMyName
is called with the concrete type, not resolve it right away (which is impossible, since the real type of T is not yet known at this point).
Upvotes: 1