如何在Scala中将定义为基类类型的变量设置为派生类型实例?

时间:2014-04-29 00:36:03

标签: scala

在Java中,我可以将变量声明为基类类型,并将其设置为派生类型实例:

public class MyClass {
    Base foo;

    public void method(){
        foo = new Derived()
    }
}

我如何在Scala中执行此操作?

1 个答案:

答案 0 :(得分:2)

class Base
class Derived extends Base

class MyClass {

  var foo: Base = _ // careful, this is null until it's initialized

  def method() = {
    foo = new Derived
  }

}