1、概述
在Scala中,trait是一种特殊的概念,它类似于Java中的接口。trait可以定义方法和字段,但是不能实例化。类可以扩展trait,从而获得trait中定义的方法和字段。
在Scala中,extend关键字用于扩展类或特质。当一个类扩展另一个类时,它继承了父类的所有字段和方法。当一个类扩展一个特质时,它必须实现特质中定义的所有抽象方法。
2、实战代码
trait ScoreQuery {
def queryScore(subject: String): Option[Double]
}
class A extends ScoreQuery {
override def queryScore(subject: String): Option[Double] = subject match {
case "语文" => Some(80)
case "数学" => Some(90)
case "英语" => Some(85)
case _ => None
}
}
class B extends ScoreQuery {
override def queryScore(subject: String): Option[Double] = subject match {
case "美术" => Some(95)
case "体育" => Some(87)
case "音乐" => Some(92)
case _ => None
}
}
class C extends ScoreQuery {
private val a = new A()
private val b = new B()
override def queryScore(subject: String): Option[Double] =
a.queryScore(subject).orElse(b.queryScore(subject)) match {
case s: Some[Double] => s
case None => subject match {
case "物理" => Some(88)
case "化学" => Some(93)
case "生物" => Some(89)
case _ => None
}
}
}
class D extends C {
private val a = new A()
private val b = new B()
override def queryScore(subject: String): Option[Double] =
super.queryScore(subject).orElse(a.queryScore(subject)).orElse(b.queryScore(subject)) match {
case s: Some[Double] => s
case None =>
subject match {
case "政治" => Some(74)
case "历史" => Some(81)
case _ => None
}
}
}
object BindTest {
def main(args: Array[String]): Unit = {
val a = new A()
val b = new B()
val c = new C()
val d = new D()
println(a.queryScore("语文"))
println(b.queryScore("体育"))
println(c.queryScore("化学"))
println(d.queryScore("政治"))
println("*" * 100)
println(c.queryScore("语文"))
println(c.queryScore("体育"))
println(d.queryScore("语文"))
println(d.queryScore("体育"))
}
}
3、控制台输出
Some(80.0)
Some(87.0)
Some(93.0)
Some(74.0)
****************************************************************************************************
Some(80.0)
Some(87.0)
Some(80.0)
Some(87.0)