scala: abstract classes instantiation?

2019-03-20 05:13发布

问题:

How it comes that I instantiate an abstract class?

  abstract class A {
    val a: Int
  }

  val a = new A {val a = 3}

Or is some concrete class implicitly created? And what do those braces after new A mean?

回答1:

With this, you implicitly extend A. What you did is syntactic sugar, equivalent to this:

class A' extends A {
    val a = 3
}
val a = new A'

These brackets merely let you extend a class on the fly, creating a new, anonymous class, which instantiates the value a and is therefore not abstract any more.



回答2:

If you know Java, this is similar to:

new SomeAbstractClass() {
    // possible necessary implementation
}

Due to Scalas uniform access it looks like you're not implementing any abstract functions, but just by giving a a value, you actually do "concretesize" the class.

In other words, you're creating an instance of a concrete subclass of A without giving the subclass a name (thus the term "anonymous" class).



回答3:

Scala allows you to create not only anonymous functions but anonymous classes too.

What you have done is simular to

class Anon extends A {
  val a = 3
} 

but without Anon name



回答4:

you're instantiating an anonymous class that inherits from A and overloads its abstract a member. For reference, see the part about anonymous class instantiations in A Tour of Scala: Abstract Types