Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of extending an anonymous type in Scala?

I'm trying to get a better understanding of Scala, and I can't seem to find a valid usecase for code like the following:

class C extends { def m() { /* ... */ } }

What is the rationale for allowing such constructs?

Thanks!

like image 953
Eyvind Avatar asked Sep 28 '11 07:09

Eyvind


People also ask

What does Extends do in Scala?

extends: The extends keyword in Scala is used to inherit features of one class by another class. baseClass extends parentClass. This extends keyword is used to inherit class while creating a new one. With: the with keyword in Scala is used when we need to inherit more than one class by another class.

What is anonymous class in Scala?

In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. Moreover an anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.

What is the purpose of anonymous class in Java?

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Can an anonymous class be declared as implementing an interface and extending a class?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.


3 Answers

I guess the only rationale here is "avoid special cases if possible". You can extend any class, an anonymous class is a class, so you can extend an anonymous class.

like image 132
Kim Stebel Avatar answered Oct 22 '22 03:10

Kim Stebel


That is not, in fact, an anonymous class! It's an early initializer and it runs as part of the constructor that goes before its superclass. Quoting the excellent answer from another stackoverflow question:

abstract class X {
    val name: String
    val size = name.size
}

class Y extends {
    val name = "class Y"
} with X

If the code were written instead as

class Z extends X {
    val name = "class Z"
}

then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class).

like image 38
leinaD_natipaC Avatar answered Oct 22 '22 05:10

leinaD_natipaC


It's called Early definitions and they deal with super class initialization order problem.

like image 34
lisak Avatar answered Oct 22 '22 05:10

lisak