Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: abstract classes instantiation?

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?

like image 785
Vadim Samokhin Avatar asked Mar 18 '12 21:03

Vadim Samokhin


People also ask

Can abstract classes be instantiated Scala?

An abstract class can also contain only non- abstract method. This allows us to create classes that cannot be instantiated, but can only be inherited. As shown in the below program. In Scala, an abstract class can contain final methods (methods that cannot be overridden).

Why do we use abstract class in Scala?

Abstract class is used to achieve abstraction. Abstraction is a process in which we hide complex implementation details and show only functionality to the user. In scala, we can achieve abstraction by using abstract class and trait.

How do you implement abstract members in Scala?

To implement Scala abstract class, we use the keyword 'abstract' against its declaration. It is also mandatory for a child to implement all abstract methods of the parent class. We can also use traits to implement abstraction; we will see that later.

Can an abstract class extend another abstract class Scala?

An abstract class can extend another abstract class. And any concrete subclasses must ensure that all abstract methods are implemented.


2 Answers

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.

like image 187
Lanbo Avatar answered Oct 13 '22 20:10

Lanbo


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

like image 22
aioobe Avatar answered Oct 13 '22 21:10

aioobe