This page is no longer maintained — Please continue to the home page at www.scala-lang.org

accessing the class in which a trait is mixed in

1 reply
gabriele renzi
Joined: 2009-07-17,
User offline. Last seen 42 years 45 weeks ago.

Hi everyone,

I've been looking around for a while but I am not sure if the answers
I found are still up to date for scala 2.8: is it possible write a
method m() in a trait T whose return type is the class in which the
trait was mixed?

E.g. in pseudo scala

trait SillyTrait {
def printAndReturn: Self = { println(this); this }
}

or

trait SillyTrait { self: UnboundT <: SillyTrait =>
def printAndReturn: UnboundT = ....
}

As far as I understand I have to write this as

trait SillyTrait[Klass] {
def printAndReturn: Klass = {...}
}

because even by using self type annotations I am unable to use an
unbound type parameter.

Am I missing something, and this is already possible in some other way?
Or, is this implicit access to the enclosing type something that is
inherently impossible in the scala type system,
or just something that is considered unnecessary since it can be
solved by using a type parameter for the trait?

Thanks in advance.

Lex
Joined: 2010-02-28,
User offline. Last seen 42 years 45 weeks ago.
Re: accessing the class in which a trait is mixed in

You can try using "this.type":

trait SimpleTrait {
def foo: this.type = { println(this); this }
}

On Sat, Oct 2, 2010 at 10:48 AM, gabriele renzi wrote:
> Hi everyone,
>
> I've been looking around for a while but I am not sure if the answers
> I found are still up to date for scala 2.8: is it possible write a
> method m() in a trait T whose return type is the class in which the
> trait was mixed?
>
> E.g. in pseudo scala
>
> trait SillyTrait {
>  def printAndReturn: Self = { println(this); this }
> }
>
> or
>
> trait SillyTrait { self: UnboundT <: SillyTrait =>
>  def printAndReturn: UnboundT = ....
> }
>
>
> As far as I understand I have to write this as
>
> trait SillyTrait[Klass] {
>  def printAndReturn: Klass = {...}
> }
>
>
> because even by using self type annotations I am unable to use an
> unbound type parameter.
>
> Am I missing something, and this is already possible in some other way?
> Or, is this implicit access to the enclosing type something that is
> inherently impossible in the scala type system,
> or just something that is considered unnecessary since it can be
> solved by using a type parameter for the trait?
>
> Thanks in advance.
>
>
> --
> blog en: http://www.riffraff.info
> blog it: http://riffraff.blogsome.com
> work: http://cascaad.com
>

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland