使用自型限定来告诉编译器特质提供了哪些方法。
示例代码:
trait Food { def name: String def taste: String = "tasty" }
case class Apple(name: String) extends Food case class Potato(name: String) extends Food { override def taste: String = "bland" }
def printFoodTaste[T <: Food](food: T): Unit = { println(s"${food.name} tastes ${food.taste}") }
val apple = Apple("Red Delicious") val potato = Potato("Yellow Potato")
printFoodTaste(apple) // prints "Red Delicious tastes tasty" printFoodTaste(potato) // prints "Yellow Potato tastes bland"