我正在努力理解apply函数是否有可能返回特定类的实例。下面是一个例子:
我有一个抽象的特质
trait BaseTrait {
def add(s: Int): Int
}
Run Code Online (Sandbox Code Playgroud)
以及两个继承此特征的类,以及:
another_methodclass Child1 extends BaseTrait {
override def add(s: Int): Int = {
s + s
}
def another_method(): Unit = {
println("Another method in Child1")
}
}
class Child2 extends BaseTrait {
override def add(s: Int): Int = {
s + s
}
def another_method(): Unit = {
println("Another method in Child2")
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试从 Base Trait 中的实用程序函数访问子类的内容时
object BaseTrait {
def apply(t: String): …Run Code Online (Sandbox Code Playgroud) scala ×1