在Scala中混合多个特征 [英] Mixing multiple traits in Scala

查看:78
本文介绍了在Scala中混合多个特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速注释:教程 假设我具有学生,工人,薪水不足和年轻的特征.

Suppose I have the traits Student, Worker, Underpaid, and Young.

我如何声明具有所有这些特征的课程(不是实例)?CollegeStudent?

How could I declare a class (not instance), CollegeStudent, with all these traits?

注意:我知道最简单的情况,例如具有一个或两个特征的CollegeStudent:

Note: I am aware of the simplests cases, such as CollegeStudent with one or two Traits:

class CollegeStudent extends Student with Worker

推荐答案

很简单,在声明一个类时,您可以根据需要随意使用"with"关键字

It is easy, when declaring a class you just use the "with" keyword as often as you want

class CollegeStudent extends Student with Worker with Underpaid with Young

如果特质改变了类的行为,特质的顺序可能很重要,这完全取决于您所使用的特质.

the order of the traits can be important if a trait is changing the behavior of the class, it all depends on traits you are using.

如果您不想拥有始终使用相同特征的类,则可以在以后使用它们:

Also if you don't want to have a class which always uses the same traits you can use them later:

class CollegeStudent extends Student
new CollegeStudent with Worker with Underpaid with NotSoYoungAnymore

这篇关于在Scala中混合多个特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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