Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of empty class in Kotlin?

Tags:

oop

kotlin

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

like image 711
imGs Avatar asked Dec 01 '17 07:12

imGs


People also ask

What is the use of empty class?

An empty class could be used as a "token" defining something unique; in certain patterns, you want an implementation-agnostic representation of a unique instance, which has no value to the developer other than its uniqueness.

What is an empty class?

Empty class: It is a class that does not contain any data members (e.g. int a, float b, char c, and string d, etc.) However, an empty class may contain member functions.

How do you make an empty class in Kotlin?

You can use the @NoArgs annotation from the no-args compiler plugin to create an empty constructor for the data class. The no-arg compiler plugin generates an additional zero-argument constructor for classes with a specific annotation.


3 Answers

Empty classes can be useful to represent state along with other classes, especially when part of a sealed class. Eg.

sealed class MyState {
    class Empty : MyState()
    class Loading : MyState()
    data class Content(content: String) : MyState()
    data class Error(error: Throwable) : MyState()
}

In this way you can think of them like java enum entries with more flexibility.

like image 88
Tom Avatar answered Sep 20 '22 14:09

Tom


An example of empty class usage from Spring Boot framework:

@SpringBootApplication
class FooApplication

fun main(args: Array<String>) {
    runApplication<FooApplication>(*args)
}
like image 27
mkrasowski Avatar answered Sep 17 '22 14:09

mkrasowski


tldr: they want to demonstrate it's possible

even an empty class is 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:

public final class Empty {
}
like image 44
s1m0nw1 Avatar answered Sep 20 '22 14:09

s1m0nw1