1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala 複数のtraitの継承先のクラスで、メソッド名が被ってしまう場合の対処

Posted at

##継承先で複数のtraitで定義したメソッド名が被った場合

下記でコンパイルするとどっちのgetInfo()を実行すべきかわからないといった意味のエラーが出力される。

//Example
trait printable {
  def getInfo() :Unit = println("now printing...")
}

trait sharable {
  def getInfo() :Unit = println("now sharing...")
}

class User extends printable with sharable

object MyApp {
  def main(arg :Array[String]) :Unit = {
    val user = new User
    user.getInfo()    
  }
}

##対処法1

superを使って、適用したいメソッドが定義されているトレイト名を継承先のクラスで指定してあげる方法。

trait printable {
  def getInfo() = println("now printing...")
}

trait sharable {
  def getInfo() = println("now sharing...")
}

class User extends printable with sharable{
  def getInfo() = super[printable].getInfo()
}

object MyApp {
  def main(arg: Array[String]) :Unit = {
    val user = new User
    user.getInfo() // "now printing..."
  }
}

##対処法2

新たにtraitで、メソッドを抽象化して定義し、各々のtraitその抽象メソッドをoverride -> 継承の流れ。

trait Common {
  def getInfo()
}

trait printable extends Common {
 override def getInfo() :Unit = println("now printing...")
}

trait sharable extends Common {
 override def getInfo() :Unit = println("now sharing...")
}

class User extends printable with sharable

object Myapp{
  def main(arg :Array[String]): Unit = {
    val user = new User
    user.getInfo() // "now sharing..."
  }
}

extendsで継承されたprintableよりも後に、読み込まれるsharableでCommonトレイトをoverrideし、具象メソッド化したgetInfo()メソッドがここでは、呼び出されるようになる。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?