如何覆盖实例的方法



是否可以覆盖某个类的实例的某个方法。

像这样的东西

class A {
val x = 1
def foo() =
x * 2
}
val a = new A()
//note i cant change class 'A' or creation of 'a'
//also 'A' has like 50 other methods that i dont wish to deal with
//so this does not work but is there some way to do it ?
val b = a extends{
override def foo() = 
x * 4
}
b.foo() // desired 4

感谢

您可以在 {} 中新建实例并覆盖(无需extend(

val b = new A {
override def foo() = x * 4
}

或者另一个想法是创建类 A 并将函数作为变量,以使其成为更通用的类。

class A(f: Int => Int) {
val x = 1
def foo() = f(x)
}

如果A定义不是sealed(并且在不同的源文件中(,那么您可以为其创建一个"包装器"。

class B(a:A) extends A {
override def foo() = x * 4
// use the a:A to extract/mirror instance data (if any)
}
val a = new A
val b = new B(a)
b.x      // res1: Int = 1  <-- acts like an A
b.foo()  // res2: Int = 4  <-- except for what's been overridden

最新更新