I'm struggling to understand if it possible for a apply
function to return an instance of a specific class. Here is an example:
I have an abstract trait
trait BaseTrait {
def add(s: Int): Int
}
and two classes that inherit this trait and:
- override an abstract method
- specify a method
another_method
class 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")
}
}
When I try to access the contents of child classes from a utility function in a Base Trait
object BaseTrait {
def apply(t: String): BaseTrait = {
t match {
case "one" => new Child1()
case "two" => new Child2()
}
}
}
val child2 = BaseTrait("one")
i don't see another_method
method
child2.another_method() // cannot resolve symbol another method
Question: is there a way in Scala (generics/lower-upper bounds) to configure an apply
method in such a way that it returns an instances of classes where it will be possible to access both overridden abstract methods AND methods belonging to this exact class (not just those that are defined in BaseTrait)