Reputation: 483
What does the following mean and how i can use it?
abstract class An_Abstract_Class {
def A_method(x : Int) : An_Abstract_Class
}
I know that there cannot be an instance or object from an abstract class, so what this method actually returns?
Can this be used for the creation of a list or a binary tree?
Is this is better techique than a concrete class and why?
Upvotes: 0
Views: 68
Reputation: 970
As you point out, this class is abstract so there can't be any direct instances of it. That means that there will need to be subclasses and those subclasses must implement A_method
. What will those subclasses return? Instances of themselves, perhaps, and since they are subclasses of An_Abstract_Class
they satisfy the return type.
For example:
class A_Concrete_Class extends An_Abstract_Class {
def A_method(x:Int) : An_Abstract_Class = this
}
Interestingly, you could also do this:
class A_Concrete_Class extends An_Abstract_Class {
def A_method(x:Int) : A_Concrete_Class = this
}
The difference is that the overridden A_method
has specified a return type of A_Concrete_Class
. Since this is a sub-class of An_Abstract_Class
the compile is fine with it. This is known as a "co-variant return type" - i.e. the return type of a sub-class implementation is allowed to be a sub-type of the base-class return type.
You can indeed use this kind of thing to implement a binary tree, though in Scala a more idiomatic approach to that would be to use a trait and case class implementations.
Upvotes: 2