Mi piacerebbe avere un tratto che può a) essere mescolato in qualsiasi classe con un metodo particolare, e b) può chiamare super. Qualcosa di simile:Tratti Scala e tipi strutturali: può un tratto estendere un tipo strutturale e quindi chiamare super?
// A and B are from a library that I don't control. No changes allowed here.
class A {
def stuff = "a stuff"
}
class B {
def stuff = "b stuff"
}
// My code starts here
type HasStuffMethod = {
def stuff: String
}
// Note that this doesn't compile - gets:
// class type required but AnyRef{def stuff: String} found
trait ImplementsStuff extends HasStuffMethod {
override def stuff = "trait + " + super.stuff
}
val a = new A with ImplementsStuff
assert(a.stuff == "trait + a stuff")
val b = new B with ImplementsStuff
assert(b.stuff == "trait + b stuff")
C'è un modo per fare questo?
Si noti che non controllo A e B; vengono da un'altra libreria che non posso modificare.
[Edit - ha aggiunto dopo aver visto le risposte]
C'è un modo per chiamare il metodo originale in qualcosa di simile?
trait ImplementsStuff {
this: HasStuffMethod =>
abstract override def stuff = "foo" + "how do I call the original method here?"
}
Questo non è utile, dal momento che quando si mescolano in qualcosa dà:
error: overriding method stuff in class A of type => java.lang.String; method stuff in trait ImplementsStuff of type => java.lang.String cannot override a concrete member without a third member that's overridden by both (this rule is designed to prevent ``accidental overrides'')
Ma non è un caso; si, voglio davvero che tu faccia un passo su quel metodo esistente. E poi lascia che lo chiami anche io.
Qui 'HasStuffMethod' non è una classe di tipo. È un alias di tipo per un tipo strutturale. – paradigmatic
A destra: un modello di tipografia è un'altra cosa. Ed è irrilevante a questa domanda se 'HasStuffMethod' è un tipo strutturale o nominale (cioè un tratto regolare). – axel22
Ho aggiunto una proposta di modifica alla tua domanda.Spero che chiarisca cosa stai cercando di fare. Se ho interpretato male puoi cancellarlo. Se è corretto, puoi usarlo per riformulare la tua domanda. In tal caso, modifica anche il riferimento a "typeclass" nel titolo della domanda. –