Scalaマルチ継承およびAOP

1179 ワード

class Human{
  println("Human")
}

trait TTeacher extends Human { 
  println("TTeacher")
  def teach 
} 

trait PianoPlayer extends Human { 
  println("PianoPlayer")
  def playPiano = {println("I am playing piano. ")} 
} 

class PianoTeacher extends Human with TTeacher with PianoPlayer { //  PianoTeacher   ,             ,     
    override def teach = {println("I am training students. ")} 
}

object UseTrait extends App{
   val t1 = new PianoTeacher
   t1.playPiano 
   t1.teach 
}

結果:Human TTeacher PianoPlayer I am playing piano.I am training students.
//AOP
trait Action { 
    def doAction 
}

trait TBeforeAfter extends Action { 
    abstract override def doAction { 
        println("Initialization") 
        super.doAction //            ,          。super.doAction      Work   ,             。
        println("Destroyed") 
    } 
}

class Work extends Action{
     override def doAction = println("Working...")
}

object UseTrait extends App{
    val work = new Work with TBeforeAfter
    work.doAction
}

結果:Initialization Working...Destroyed