6

9月 | 2016 | 炒饭的小站

 3 years ago
source link: https://blog.chaofan.io/archives/2016/09
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
9月 | 2016 | 炒饭的小站

Scala对象初始化时访问成员的坑

先看如下代码:

class InitializationTest {
  abstract class Base {
    method()
    def method(): Unit
  class Subclass extends Base {
    val obj = new Object
    override def method(): Unit = {
      println(obj)
  @Test
  def doTest(): Unit = {
    new Subclass()

以doTest为入口,这个程序的输出是: null 和期望不一样啊! 原因是Scala以整个类中的内容为构造方法,执行顺序是从基类到子类。运行method时,obj还没有初始化,于是就返回了null。 因为obj不可变,所以这里也不能直接初始化。真正的解决方法是使用lazy关键字,它可以让成员在第一次使用时被初始化。 […]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK