🚙 · Basic class syntax

1 min read · Updated on by

Read on to learn the basic syntax of classes in Kotlin, how the constructor is treated as a function, and how empty class bodies are defined.

Classes in Kotlin reflect their counterparts in Java to a certain degree, but are designed with brevity in mind, and the way they are written differs in certain aspects. On top of that, Kotlin adds a couple of features that are not available in Java, which makes classes in Kotlin more powerful than their Java counterparts.

But we’ll get to that. For now, let’s start with the basics.


//sampleStart
// Defines a new class with a single property.
class TestClass {
    var myInteger: Int = 0

    fun decrementAndGet() = --myInteger
}

// There is no new keyword in Kotlin - the 'TestClass' bellow is a constructor,
// which is a function, and it is called as such.
val instance = TestClass()

fun createInstanceOfMyClass(constructorFun: () -> TestClass) = constructorFun()
val alsoInstance = createInstanceOfMyClass(::TestClass) // Works

// Properties are public by default
val myIntegerIncremented = ++instance.myInteger
// So are functions
val zero = instance.decrementAndGet()

class EmptyClass { }
// Classes with empty bodies can omit the curly braces
class AlsoEmptyClass

abstract class AbstractClass {
    abstract fun draw()
}
//sampleEnd
fun main() {
    val poem = """
        In the kingdom of types, Kotlin reigns,
        With null safety, no more coding pains.
        From data classes to enums so fine,
        In the world of programming, it's a gold mine!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer