码迷,mamicode.com
首页 > 其他好文 > 详细

trait

时间:2015-08-01 18:49:38      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

技术分享语法上讲像接口,使用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

 

trait

标签:

原文地址:http://www.cnblogs.com/thinkpad/p/4694475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!