10

In Kotlin both the header and the body are optional; if the class has no body, curly braces can be omitted.

So we can define class like,

class Empty

What is the use of this type of class?

paril
  • 1,850
  • 2
  • 14
  • 26

2 Answers2

16

You can use it for some custom exceptions:

class Empty : Exception()

or as a marker interface:

interface Empty

or as a data class:

data class Empty(val s: String)

or as a marker annotation:

annotation class Empty

~ That's a good post to read.

Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
3

Kotlin allows to declare any type without body, for example:

interface Interface;

class Class;

annotation class Annotation;

sealed class SealedClass;

data class DataClass(var value: String);

object ObjectClass;

enum class EnumClass;

class CompanionClass {
    companion object
}

the usage of each definition can be described as below:

  • interface - as a marker interface.
  • annotation - describe the annotated type has some ability. e.g: junit4 @Before and @After annotations.
  • object - it often present as a token or a lock or a placeholder and .etc. e.g: synchronized(lock){ /*thread safe working*/ }
  • data class - quickly define a java POJO class with getters, setters? , equals, hashCode, toString and componentN operators for destructuring in kotlin.
  • others - they are meaningless, just are the language syntax.
holi-java
  • 29,655
  • 7
  • 72
  • 83