在抽象类上使用特征的优点是什么? [英] What are the pros of using traits over abstract classes?

查看:47
本文介绍了在抽象类上使用特征的优点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下Scala中的特质吗?与扩展抽象类相比,trait 有哪些优势?

Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?

推荐答案

简而言之,您可以使用多个特征——它们是可堆叠的".另外,traits 不能有构造函数参数.

The short answer is that you can use multiple traits -- they are "stackable". Also, traits cannot have constructor parameters.

以下是特征的堆叠方式.请注意,特征的顺序很重要.他们会从右到左互相呼叫.

Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.

class Ball {
  def properties(): List[String] = List()
  override def toString() = "It's a" +
    properties.mkString(" ", ", ", " ") +
    "ball"
}

trait Red extends Ball {
  override def properties() = super.properties ::: List("red")
}

trait Shiny extends Ball {
  override def properties() = super.properties ::: List("shiny")
}

object Balls {
  def main(args: Array[String]) {
    val myBall = new Ball with Shiny with Red
    println(myBall) // It's a shiny, red ball
  }
}

这篇关于在抽象类上使用特征的优点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆