Scala 特征混合器
我们可以用一个类或一个抽象类来扩展一些scala traits,这就是所谓的trait Mixins。值得一提的是,只有特征或特征与类的混合,或特征与抽象类的混合才能被我们扩展。这里甚至必须保持trait Mixins的顺序,否则编译器会抛出一个错误。
注意。
- 混合特征是用来组成一个类的。
- 一个类很难有一个单一的超类,但它可以有许多特征混合体。超类和特征Mixins可能有相同的超类型。
现在,让我们看看一些例子。
- 用trait扩展抽象类
例子 :
// Scala program of trait Mixins
// Trait structure
trait Display
{
def Display()
}
// An abstract class structure
abstract class Show
{
def Show()
}
// Extending abstract class with
// trait
class CS extends Show with Display
{
// Defining abstract class
// method
def Display()
{
// Displays output
println("GeeksforGeeks")
}
// Defining trait method
def Show()
{
// Displays output
println("CS_portal")
}
}
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating object of class CS
val x = new CS()
// Calling abstract method
x.Display()
// Calling trait method
x.Show()
}
}
输出:
GeeksforGeeks
CS_portal
在这里,Mixins的正确顺序是,我们需要先扩展任何类或抽象类,然后通过使用关键字with扩展任何特征。
- 在没有trait的情况下扩展抽象类
示例 :
// Scala program of trait Mixins
// Trait structure
trait Text
{
def txt()
}
// An abstract class structure
abstract class LowerCase
{
def lowerCase()
}
// Extending abstract class
// without trait
class Myclass extends LowerCase
{
// Defining abstract class
// method
def lowerCase()
{
val y = "GEEKSFORGEEKS"
// Displays output
println(y.toLowerCase())
}
// Defining trait method
def txt()
{
// Displays output
println("I like GeeksforGeeks")
}
}
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating object of 'Myclass'
// with trait 'Text'
val x = new Myclass() with Text
// Calling abstract method
x.lowerCase()
// Calling trait method
x.txt()
}
}
输出:
geeksforgeeks
I like GeeksforGeeks
因此,从这个例子中我们可以说,特征甚至可以在创建对象时被扩展。
注意:如果我们先扩展trait,然后再扩展抽象类,那么编译器会抛出一个错误,因为这不是trait Mixins的正确顺序。
极客教程