Any way for trait to get the class of an abstract type?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Any way for trait to get the class of an abstract type?

Nils Kilden-Pedersen
Given this trait, is there any way to get the class at runtime?

trait Foo {
  type Bar

  def sayHello() {
    println("I'm using type " + classOf[Bar]) // This obviously doesn't work
  }
}

Some magic with manifests perhaps?

Reply | Threaded
Open this post in threaded view
|

Re: Any way for trait to get the class of an abstract type?

Naftoli Gugenheim
scala> trait Foo { type Bar; def sayHello(implicit m: Manifest[Bar]) {println(m.erasure)} }
defined trait Foo

scala> new Foo {}.sayHello
<console>:7: error: could not find implicit value for parameter m: scala.reflect.Manifest[_1.Bar]
       new Foo {}.sayHello
                  ^

scala> class C extends Foo { type Bar = String }
defined class C

scala> new C().sayHello
class java.lang.String


On Thu, Jan 6, 2011 at 10:38 AM, Nils Kilden-Pedersen <[hidden email]> wrote:
Given this trait, is there any way to get the class at runtime?

trait Foo {
  type Bar

  def sayHello() {
    println("I'm using type " + classOf[Bar]) // This obviously doesn't work
  }
}

Some magic with manifests perhaps?


Reply | Threaded
Open this post in threaded view
|

Re: Any way for trait to get the class of an abstract type?

Nils Kilden-Pedersen
On Thu, Jan 6, 2011 at 4:55 PM, Naftoli Gugenheim <[hidden email]> wrote:
scala> trait Foo { type Bar; def sayHello(implicit m: Manifest[Bar]) {println(m.erasure)} }
defined trait Foo

scala> new Foo {}.sayHello
<console>:7: error: could not find implicit value for parameter m: scala.reflect.Manifest[_1.Bar]
       new Foo {}.sayHello
                  ^

scala> class C extends Foo { type Bar = String }
defined class C

scala> new C().sayHello
class java.lang.String


That's cool, but can it be done without changing the signature of sayHello() AND without the implementing class doing anything?
Reply | Threaded
Open this post in threaded view
|

Re: Any way for trait to get the class of an abstract type?

Naftoli Gugenheim
Not that I can see how.


On Thu, Jan 6, 2011 at 10:35 PM, Nils Kilden-Pedersen <[hidden email]> wrote:
On Thu, Jan 6, 2011 at 4:55 PM, Naftoli Gugenheim <[hidden email]> wrote:
scala> trait Foo { type Bar; def sayHello(implicit m: Manifest[Bar]) {println(m.erasure)} }
defined trait Foo

scala> new Foo {}.sayHello
<console>:7: error: could not find implicit value for parameter m: scala.reflect.Manifest[_1.Bar]
       new Foo {}.sayHello
                  ^

scala> class C extends Foo { type Bar = String }
defined class C

scala> new C().sayHello
class java.lang.String


That's cool, but can it be done without changing the signature of sayHello() AND without the implementing class doing anything?