Is there such a thing as "Limitless Type"?

I would like to define a trait Renamable

while maintaining some classes that require a modified name field. Here's my first shot:

trait Renamable {
    self =>
    var name:String = _

    def withName(name:String) = {
        self.name = name
        self
    }
}

class Person extends Renamable {
    def sayHello = println(s"Hello, i am $name")
}

      

My problem is that the return type withName()

is inferred to Renamable

, preventing me from chaining method calls like this:

new Person().withName("Julio").sayHello 
//Error: value sayHello is not a member of Renamable

      

I read that I have an annotation of type self and use it as a return type, but I don't know in advance what types will be used. I would like the return to be the same as a class using a trait, no constraints.

Can I have "unlimited types"?

+3


source to share


1 answer


You can use this.type

(might self.type

work too). The only valid value of this type is this

and therefore allows the invocation site to know that the return value is the recipient of the invocation:



trait Renamable {
    var name:String = _

    def withName(name:String): this.type = {
        this.name = name
        this
    }
}

      

+8


source







All Articles