LoginSignup
0
0

More than 5 years have passed since last update.

traitの持ち物が衝突したときの振る舞いについて

Posted at

下記は動作する

LegalBuz.scala
package test

trait Foo {
  def hello = "foo"
}

trait Bar {
  def hello = "bar"
}

class Buz extends Foo with Bar{

  override val hello = super[Foo].hello

  def sayHello():Unit = {
    println(hello)
  }
}

object RunBuz extends App{
  new Buz().sayHello()
}

FooとBarのdefをvalにしてみると動作しない

IllegalBuz.scala
package test

trait Foo {
  val hello = "foo"
}

trait Bar {
  val hello = "bar"
}

class Buz extends Foo with Bar{

  override val hello = super[Foo].hello

  def sayHello():Unit = {
    println(hello)
  }
}

object RunBuz extends App{
  new Buz().sayHello()
}
error: super may be not be used on value hello
override val hello = super[Foo].hello

may be not be...?

下記も動く(結果はbuz)

YetAnotherLegalBuz.scala
package test

trait Foo {
  val hello = "foo"
}

trait Bar {
  val hello = "bar"
}

class Buz extends Foo with Bar{

  override val hello = "buz"

  def sayHello():Unit = {
    println(hello)
  }
}

object RunBuz extends App{
  new Buz().sayHello()
}

valをリテラルで置き換えることはできるけど、どちらかのtraitで宣言されているものは参照できないのか?
と思っていたら
https://issues.scala-lang.org/browse/SI-1938
こういうのがあったので、やはりできなかったというお話。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0