如何覆盖实例

时间:2017-08-25 07:34:32

标签: scala

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

像这样的东西

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

THX

2 个答案:

答案 0 :(得分:3)

如果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

答案 1 :(得分:3)

您可以在{}内添加新实例并覆盖(无需extend

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

或者另一个想法是使用函数作为变量创建类A,使其更具通用性。

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