第八课:scala接口实战

来源:互联网 发布:快乐十分源码 编辑:程序博客网 时间:2024/05/29 15:58

     在学习scala接口之前,先介绍一下,scala的的接口和Java中的接口的概念和java不太一样,首先它采用关键字trait来定义一个接口,其次。trait中可以直接实现方法。让我们一起来看三段Spark源码,分别来自SparkContext.scala、Logging.scala、ExecutorAllocationClient.scala这三个类中。看完后一起来总结scala trait的一些特性。


SparkContext.scala

<span style="font-family:Microsoft YaHei;font-size:12px;">class SparkContext(config: SparkConf) extends Logging with ExecutorAllocationClient {</span>
<span style="font-family:Microsoft YaHei;font-size:12px;"></span>
<span style="font-family:Microsoft YaHei;font-size:12px;">}</span>


Logging.scala

<span style="font-family:SimSun;font-size:14px;">trait Logging {  @transient private var log_ : Logger = null  protected def logName = {    this.getClass.getName.stripSuffix("$")  }  protected def log: Logger = {    if (log_ == null) {      initializeIfNecessary()      log_ = LoggerFactory.getLogger(logName)    }    log_  }</span>


ExecutorAllocationClient.scala

private[spark] trait ExecutorAllocationClient {  private[spark] def requestTotalExecutors(      numExecutors: Int,      localityAwareTasks: Int,      hostToLocalTaskCount: Map[String, Int]): Boolean  def requestExecutors(numAdditionalExecutors: Int): Boolean  def killExecutors(executorIds: Seq[String]): Boolean

从这三段代码,我们可以看出,Scala的Trait的实现是通过extends关键字实现的,如果需要实现多个trait,在使用with关键字(with一般叫做混入),形式如:()

class Test extends trait_1 with trait_2 {
}
另外,我们看Logging 和 ExecutorAllocationClient 这两个trait,对比可以发现。scala的trait 定义的方法可以直接在trait中实现,也可以定义一个我们抽象的方法,然后具体使用的时候再实现。

这里需要注意的是,scala的接口支持多重继承,但是,类不支持多重继承。接口的继承有个特点,就是成员直接被继承过来了,但是类的继承的时候,父类的成员还是父类的成员

如果我们要定义一个抽象的成员或者方法,不用使用abstract 关键字。直接定义,并且声明放回类型就行了。如ExecutorAllocationClient中那样,

def requestExecutors(numAdditionalExecutors: Int): Boolean

如果定义的是成员则如下所示即可,定义完抽象属性后,在继承后一定要对其进行赋值。

val name: String
如果trait中的方式都已经实现了的话,一般我们把这个trait作为工具类来使用(如上面的Logging),如果没有实现trait中的方法的话,作为接口来使用,这是scala的trait功能和java接口的差别之一。


scala的类的实例对象也可以混入接口,以扩展当前对象实例的功能。

package com.dt.spark/**  * Created by DT_Spark on 16-8-4.  */object HelloTrait {  def main(args: Array[String]) {    val person = new Loggin("DT_Spark") with RichLogger //类的实例对象,混入接口。可以随时扩展第三方接口的功能    person.loggin  }}trait Logger {  def log(message: String){    println("Logger: " + message)  }}trait RichLogger extends Logger{  override def log(message: String){    println("RichLogger: " + message)  }}class Loggin(val name: String) extends Logger{  def loggin{    println("Hi welcome !" + name)    log(name)  }}


scala的多重继承方法实现顺序是从右往左实现的。trait中所有抽象方法实现的时候都要写override关键字。


0 0
原创粉丝点击