0

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 :)

hqt
  • 29,632
  • 51
  • 171
  • 250

1 Answers1

1

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

If I understand correctly, you are talking about plain inheritance polymorphism. You can assign this reference to a value in your case, or just use it directly:

abstract class A {
  def functionA {
    this.functionB
  }

  def functionB {
    print("hello")
  }
}

class C extends A{
}

object Main extends App {
  val c : C = new C()
  c.functionB
  c.functionA
}

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):

abstract class A {
  def functionA {
    val a : A = create()
    a.functionB
  }

  def functionB {
    print("hello")
  }

  def create(): A
}

class C extends A {
  override def create() = new C
}

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.

Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296