nob nob - 3 years ago 129
Scala Question

Figuring out type of overriden member variable in Scala

I have a type hierarchy like this:

trait Description {


trait DescriptionProvider {
val description: Description

object Sample extends DescriptionProvider {
object description extends Description {
val name = "foo"

Now I am looking for a function
, which gives me the concrete value
for any sub type of
, including it's type.

should compile and evaluate to

An obvious accessing method can't work of course

def obvious[T <: DescriptionProvider](x: T) = x.description
obvious(Sample).name // doesn't compile of course, as foo returns only Description.

Is there any Trick how to design such a function f without doing massive changes in the object hierarchy (which is already existent and huge)?

I already tried using a Macro, which somehow works, but IntelliJ doesn't like it (in above Example
would appear in Red), which makes it pretty hard to use.

I am using Scala 2.10 and can't change right now.

Answer Source

Annotate your return type with a path-dependent one instead of relying on inference:

def obvious[T <: DescriptionProvider](x: T): x.description.type = x.description

I made a Scastie snippet with 2.10.6 and it seems to be working. I cannot check if Intellij would not complain, however.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download