Me gustaría tener un rasgo que pueda a) mezclarse en cualquier clase con un método particular, yb) llamar súper. Algo como esto:Características de Scala y tipos estructurales: ¿puede un rasgo extender un tipo estructural y luego llamar a 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")
¿Hay alguna manera de hacer esto?
Tenga en cuenta que no controlo A y B; vienen de otra biblioteca que no puedo modificar.
[Editar - añadió después de ver respuestas]
¿Hay alguna manera para llamar al método original en algo como esto?
trait ImplementsStuff {
this: HasStuffMethod =>
abstract override def stuff = "foo" + "how do I call the original method here?"
}
Esto no es útil, ya que cuando se mezclan en algo que da:
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'')
Pero no es casualidad; sí, realmente quiero que recorras todo ese método existente. Y luego déjame llamarlo también.
Aquí 'HasStuffMethod' no es un tipo de clase. Es un alias tipo a un tipo estructural. – paradigmatic
Derecha: un patrón de clase de letra es otra cosa. Y es irrelevante para esta pregunta si 'HasStuffMethod' es un tipo estructural o nominal (es decir, un rasgo regular). – axel22
He agregado una edición propuesta a su pregunta.Espero que aclare lo que estás tratando de hacer. Si he malinterpretado, puedes borrarlo. Si es correcto, puede usarlo para reformular su pregunta. En ese caso, edite también la referencia a "typeclass" en el título de la pregunta. –