IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]一天一段scala代码(十)

    linger2012liu发表于 2015-03-09 18:27:26
    love 0
    一天一段scala代码(十)

    为了更好的驾驭spark,最近在学习scala语言特性,主要看《快学scala》,顺便把一些自己认为有用的代码记下来。


    package examples
    
    
    //特质的基本使用
    
    trait Logger
    {
      def log(msg:String)   //不定义,抽象方法
    }
    
    class ConsoleLogger extends Logger
    {
      def log(msg:String){println(msg)}  //重写抽象方法不需要override
    }
    
    class Animal
    {}
    
    
    import scala.util.logging.Logged
    
    class Cat extends Animal with Logged
    {
        def sayHello=
        {
          log("Fuck!")
        }
    }
    
    trait ConsoleLogged extends Logged
    {
      override def log(msg:String){println(msg)} //因为Logged中log不是抽象方法,所以需要override
    }
    
    //Ordered接口的使用
    class Rational(n:Int,d:Int) extends Ordered[Rational]
    {
      def numer =n
      def demon = d
      def compare(that:Rational)=
      {
        this.numer*that.demon - that.numer*this.demon
      }
    }
    
    
    //特质作堆叠
    abstract class IntQueue
    {
      def get():Int
      def put(x:Int)
    }
    
    import scala.collection.mutable.ArrayBuffer
    class BasicIntQueue extends IntQueue
    {
      private val buffer = new ArrayBuffer[Int]
      def get=buffer.remove(0)
      def put(x:Int)={buffer+=x}
    }
    
    trait Incrementing extends IntQueue
    {
      abstract override def put(x:Int)  {super.put(x+1)}
    }
    
    trait Filtering extends IntQueue
    {
      abstract override def put(x:Int)
      {
        if(x>=0) super.put(x)
      }
    }
    
    
    object Example10 extends App{
    
      var cat = new Cat
      cat.sayHello //没输出,因为Logged里面的log没有输出
      
      println("------------------------")
      cat = new Cat with ConsoleLogged
      cat.sayHello //有输出,因为ConsoleLogged里面的重写了log,覆盖了原Logged
      
      println("------------------------")
      val half = new Rational(1,2)
      val third = new Rational(1,3)
      println(half>third)
      
      println("------------------------")
      var queue = new BasicIntQueue with Incrementing with Filtering  //先过滤再递增再进队列
      queue.put(-1)
      queue.put(0)
      queue.put(1)
      println(queue.get)
      println(queue.get)
      
      println("------------------------")
      queue = new BasicIntQueue with Filtering  with Incrementing //先递增再过滤再进队列
      queue.put(-1)
      queue.put(0)
      queue.put(1)
      println(queue.get)
      println(queue.get)
      
      //从上面可以看出来,越在后面的特质越先起作用
      //如果她调用了super,然你就会接着调用她左边的特质的对应方法
      
    }

    输出
    ------------------------
    Fuck!
    ------------------------
    true
    ------------------------
    1
    2
    ------------------------
    0
    1
    



    本文作者:linger
    本文链接:http://blog.csdn.net/lingerlanlan/article/details/44158021



沪ICP备19023445号-2号
友情链接