- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
accessing the class in which a trait is mixed in
Sat, 2010-10-02, 15:49
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.
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
>