特质(trait)

33 阅读1分钟
object Main {
  trait BeautifulEye {
    val eye: String = "眼睛漂亮"
  }
  
  trait Tall {
    val height: String = "大高个"
  }
  
  class Child extends BeautifulEye with Tall
  
  def main(args: Array[String]): Unit = {
    val child = new Child()
    println(child.eye)    // 眼睛漂亮
    println(child.height) // 大高个
  }
}

1. 定义特质

scala

trait BeautifulEye {
  val eye: String = "眼睛漂亮"
}

trait fail {
  val height: String = "大高个"
}
  • 定义了两个特质:BeautifulEye 和 fail
  • 每个特质都包含一个具体的字段值

2. 类继承特质

scala

class Child extends BeautifulEye with fail
  • Child类使用 extends 和 with 关键字继承多个特质
  • 这是Scala实现多重继承的语法

特质(trait)是Scala中非常重要的特性,它可以包含:

  • 抽象方法
  • 具体方法
  • 字段
  • 与其他特质组合