scala: abstract classes instantiation?

后端 未结 4 537
灰色年华
灰色年华 2021-02-04 15:46

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 cla

相关标签:
4条回答
  • 2021-02-04 15:56

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

    0 讨论(0)
  • 2021-02-04 16:00

    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

    0 讨论(0)
  • 2021-02-04 16:02

    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

    0 讨论(0)
  • 2021-02-04 16:10

    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.

    0 讨论(0)
提交回复
热议问题