scala特质
Scala特质 (Scala traits)
Traits in Scala are like interfaces in Java. A trait can have fields and methods as members, these members can be abstract and non-abstract while creation of trait.
Scala中的特性类似于Java中的接口 。 特征可以具有作为成员的字段和方法,这些成员在特征创建时可以是抽象的且非抽象的。
The implementation of Scala traits can implement a trait in a Scala Class or Object.
Scala特征的实现可以在Scala类或对象中实现特征。
Some features of Scala traits:
Scala特征的一些特征:
Members can be abstract as well as concrete members.
成员可以是抽象成员,也可以是具体成员。
A trait can be extended by another trait.
一个特性可以被另一个特性扩展。
Made using "trait" keyword.
使用“ trait”关键字制成。
Syntax:
句法:
trait trait_name{
def method()
}
Example showing the use of trait
示例显示特质的使用
This example is taken from https://docs.scala-lang.org/tour/traits.html
此示例取自https://docs.scala-lang.org/tour/traits.html
trait Iterator[A] {
def hasNext: Boolean
def next(): A
}
class IntIterator(to: Int) extends Iterator[Int] {
private var current = 0
override def hasNext: Boolean = current < to
override def next(): Int = {
if (hasNext) {
val t = current
current += 1
t
} else 0
}
}
val iterator = new IntIterator(10)
iterator.next() // returns 0
iterator.next() // returns 1
This example shows the use of trait and how it is inherited? The code creates a trait name Iterator, this trait there are 2 abstract methods hasNext and next. Both the methods are defined in the class IntInterator which defines the logic. And then creates objects for this class to use the trait function.
这个例子展示了特质的使用以及它是如何被继承的? 该代码创建一个特征名称Iterator ,此特征有2个抽象方法hasNext和next 。 这两种方法都在定义逻辑的IntInterator类中定义。 然后创建此类的对象以使用trait函数 。
Another working example,
另一个工作示例
trait hello{
def greeting();
}
class Ihelp extends hello {
def greeting() {
println("Hello! This is include Help! ");
}
}
object MyClass {
def main(args: Array[String]) {
var v1 = new Ihelp();
v1.greeting
}
}
Output
输出量
Hello! This is include Help!
This code prints "Hello! This is include Help!" using trait function redefinition and then calling that function.
该代码显示“您好!这包括帮助!”。 使用特征函数重新定义 ,然后调用该函数。
Some pros and cons about using traits
关于使用特质的一些利弊
Traits are a new concept in Scala so they have limited usage and less interoperability. So, for a Scala code That can be used with a Java code should not use traits. The abstract class would be a better option.
特质是Scala中的一个新概念,因此用途有限且互操作性较低。 因此,对于可与Java代码一起使用的Scala代码,不应使用特征。 抽象类将是一个更好的选择。
Traits can be used when the feature is to be used in multiple classes, you can use traits with other classes too.
性状时,可以使用该功能是在多个类别中使用,可以使用与其他类的特征了。
If a member is to be used only once then the concrete class should be used rather than a Traits it improves the efficiency of the code and makes it more reliable.
如果一个成员仅使用一次,则应使用具体的类而不是Traits,这将提高代码的效率并使其更可靠。
翻译自: https://www.includehelp.com/scala/traits-in-scala.aspx
scala特质