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特質