I was going through Kotlin
reference document and then I saw this.
The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces. Both the header and the body are optional; if the class has no body, curly braces can be omitted.
class Empty
Now I'm wondering what is the use of such class declaration without header and body
It doesn't make much sense as a final result. However it can be useful in active development and at a design time as a placeholder of some sort, which may be expanded in the future. Such terse syntax allows you to quickly define such new types as needed. Something like:
I think main reason this is specifically mentioned in documentation is to demonstrate, that language syntax in general can be terse, not that it is specifically created for common usage.
Empty classes can be useful to represent state along with other classes, especially when part of a sealed class. Eg.
In this way you can think of them like java enum entries with more flexibility.
An example of empty class usage from Spring Boot framework:
From practical programmer day to day perspective empty class makes no much sense indeed. There are however cases where this behavior is desirable.
There are scenarios where we want to make sure that we want to define a class and at the same time, we want to make sure that instance of this class will never be created (type created from such class is called
empty type
oruninhabited type
).Perfect example of this is Kotlin
Nothing
class with do not have class declaration header and body (notice that it also have private constructor) https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/Nothing.ktThere are few usages for
Nothing
in Kotlin language. One of them would be a function that does not return a value (do not confuse this withUnit
where the function returns actually returns a value of typeUnit
). A typical example is anassertFail
method used for testing or method that exits current process. Both methods will never actually return any value yet we need to explicitly say tell it to a compiler using special type (Nothing
).Nothing can be also used with start projections where type
Function<*, String>
can be in-projected toFunction<in Nothing, String>
Another usage for empty class is type token or placeholder:
Some languages are using empty classes for metaprogramming although I haven't explored this part personally: Advantages of an empty class in C++
tldr: they want to demonstrate it's possible
It's still of type
Any
and therefore has certain methods automatically. I think in most cases, this does not make sense, but in the documentation case it's used to show the simplest possible definition of a class.The Java equivalent would be: