Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - What is the use of class without body?

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?

like image 553
paril Avatar asked Jun 28 '17 11:06

paril


People also ask

What is the use of data class in Kotlin?

A Kotlin Data Class is used to hold the data only and it does not provide any other functionality apart from holding data. There are following conditions for a Kotlin class to be defined as a Data Class: The primary constructor needs to have at least one parameter.

What is the difference between object and class in Kotlin?

Classes provide blueprints from which objects can be constructed. An object is an instance of a class that consists of data specific to that object. You can use objects or class instances interchangeably.

What is the difference between interface and abstract class in Kotlin?

Kotlin interfaces are similar to abstract classes. However, interfaces cannot store state whereas abstract classes can. Meaning, interface may have property but it needs to be abstract or has to provide accessor implementations. Whereas, it's not mandatory for property of an abstract class to be abstract.

How do classes work in Kotlin?

Kotlin class A class is a blueprint for an object; it shares common properties and behaviour in form of members and member functions. In Kotlin, a class is declared with the class keyword. The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.)


2 Answers

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.

like image 172
Alexander Romanov Avatar answered Oct 01 '22 11:10

Alexander Romanov


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.
like image 38
holi-java Avatar answered Oct 01 '22 11:10

holi-java