简体   繁体   English

在Scala中扩展对象实例的类

[英]Extend the class of an object instance in scala

Say I have an instance of a class that has many methods and I want to extend the behaviour of say one method in that object. 假设我有一个类的实例,该实例具有许多方法,并且我想扩展该对象中某个方法的行为。 In java I guess I would have to create a wrapper that redirects all calls to the instance and I could then redefine the relevant method in the wrapper. 在Java中,我想我必须创建一个包装器,将所有调用重定向到该实例,然后可以在包装器中重新定义相关方法。 But I was wondering if in scala there was some other cleverer way to do this? 但是我想知道在Scala中是否还有其他更聪明的方法可以做到这一点?

so eg 所以例如

class A {
  def x = 1
  def y = 2
  def z = 3
}

val a = new A

val a2 = wrap(a) { override def z = 4 } // ???

Regards Des 问候德斯

In Java we have the ability to extend an entire class. 在Java中,我们可以扩展整个类。 It is up to the programmer to decide which methods become overridden. 由程序员决定哪些方法被重写。 We use the "extends" keyword to perform this task. 我们使用“ extends”关键字来执行此任务。

ie

public class A
{
  public void method1(){...}
  public void method2(){...}
}

public class B extends A
{
  public void method2(){...}
  public void method3(){...}
}

Here for class B we use the extends keyword. 在这里,对于B类,我们使用extend关键字。 Due to inheritance, class B inherits method1, and in this case overwrites method2 and has added another method called method3. 由于继承,类B继承了method1,在这种情况下,该类将覆盖method2并添加了另一个称为method3的方法。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM