语法上讲像接口,使用extends或with
trait Logger{def log(msg:String){}}
class Student extends Person with Logger{
def hello(name:String)log(name)
}
混入语法(mix-in)
new Student with ConsoleLogger
new Student with FileLogger
1 trait Logger{ 2 def log(words:String){} 3 } 4 5 trait ConsoleLogger extends Logger{ 6 override def log(words:String){println("writing in console:"+words)} 7 } 8 9 10 trait FileLogger extends Logger{ 11 override def log(words:String){println("writing to file, contents :"+words)} 12 } 13 14 class Homework extends Logger{ 15 def dohome(sth:String){log(sth)} 16 } 17 18 (new Homework with ConsoleLogger).dohome("homework")//writing in console:homework
19 (new Homework with FileLogger).dohome("homework")//writing to file, contents :homework
时间: 2024-11-05 22:42:54