Scala特征混合顺序和超级调用 [英] Scala traits mixin order and super call

查看:88
本文介绍了Scala特征混合顺序和超级调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

trait base{
  def msg: Unit= {
    println{"base"}
  }
}

trait foo extends base {
  abstract override def msg: Unit ={
    super.msg
    println("foo")
  }
}

class base2{
  def msg:Unit = {
    println{"base 2"}
  }
}

class test extends base2 with foo{
   override def msg: Unit ={
    super.msg
    println("done")
  }
}

如果我拨打(new test).msg,这将打印出如下内容:base, foo, done

If I call (new test).msg, this prints out things like: base, foo, done

但是,如果我将基本特征更改为:

However, if I change the base trait to:

trait base{
  def msg: Unit
}

它打印出如下内容:base 2, foo, done

我知道with的顺序是从右到左(最后一个在前),但是extends呢?为什么有时会打印base2,但有时会打印base?

I understand the order of with is from right to left (last one comes first) but how about extends? How come sometimes it prints base2, but sometimes base?

推荐答案

Scala称为类型线性化.它定义了初始化顺序.在此处阅读 http://eed3si9n.com/constraining-class-linearization-in-Scala

Scala has something called type linearization. It defines initialization order. Read here http://eed3si9n.com/constraining-class-linearization-in-Scala

这篇关于Scala特征混合顺序和超级调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆