For example I have this code :
abstract class A {
def functionA() {
val a : A = null; // take null just for temporary, because I cannot think what should to put here
a.functionB
}
def functionB() {
print("hello")
}
}
class C extends A{
}
object Main extends App {
val c : C = new C()
c.functionB // print hello
c.functionA // ERROR
}
at functionA, I want declare a object in case : if the current class is C, a will have type C. if the current class is D, a will have type D. Because I cannot do :
val a : A = new A // because A is abstract
In Java, I can do this easily, but I cannot do like that in Scala. Please help me this.
Thanks 🙂
If I understand correctly, you are talking about plain inheritance polymorphism. You can assign
thisreference toavalue in your case, or just use it directly:In this case there will be no
NullPointerException.However, if you really want to create new object of the real type inside base class, you should use inheritance polymorphism in other way (I think this is somewhat simpler than whan @brunoconde suggested, but the idea is very similar; I don’t think that generics are really needed here):
This is what I’d do in Java if I had to. You have to override
create()method in every child class though. I doubt that it is possible to do this without overriding while not resorting to reflection.