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

一天一段scala代码(十)

时间:2015-03-09 19:08:40      阅读:129      评论:0      收藏: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

一天一段scala代码(十)

标签:

原文地址:http://blog.csdn.net/lingerlanlan/article/details/44158021

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