liveBook · Manning

Class

As explained in Kotlin in Action, 2E

A class is a Kotlin declaration that defines the structure and behavior of objects through members such as properties, functions, and constructors.

A Kotlin class groups an object’s data and behavior. For simple data holders, a primary constructor can declare properties directly, eliminating the field assignment, constructor body, and getter boilerplate familiar from Java. section 2.2 section 2.6

A compact class

class Person(val name: String) Person has a primary constructor parameter, name, and val makes that parameter a read-only property. Public visibility is the default, so no public modifier is required. section 2.2

The primary constructor is the parenthesized part after the class name. It accepts constructor parameters and can create properties from them. When initialization needs more than a direct assignment, place that code in one or more init blocks; they run when an instance is created. section 4.2.1

Properties, defaults, and construction

class User( val nickname: String, val isSubscribed: Boolean = true ) val alice = User("Alice") val bob = User("Bob", false) val carol = User("Carol", isSubscribed = false) Default values make arguments optional, and named arguments make a call explicit without requiring positional order. section 4.2.1

A class name and a type are related but not identical. A nongeneric class name can name a type, while nullable forms create another type, such as String?. Generic classes require type arguments: List is a class, whereas List<Int> and List<String?> are types. Subtype rules determine which values can be assigned or passed as arguments. section 11.3.2 section 11.3.2

class User constructor(_nickname: String) {    #1
    val nickname: String
 
    init {                                     #2
        nickname = _nickname
    }
}

Compare the explicit constructor, property, and init block form with the compact primary-constructor form to see exactly what the shorthand replaces. section 4.2.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains primary constructors, properties, initializer blocks, defaults, and type distinctions; defers fuller class details.
Examples
Uses Person and User declarations, including explicit initialization, default constructor values, and named-argument calls.
What it assumes
Starts with basic class declaration while assuming enough Kotlin syntax to read properties, parameters, and types.
What you can do after
Build Kotlin classes with constructor-backed properties, initialization code, defaults, and named constructor arguments.
How it connects
Connects classes with properties, constructors, initializer blocks, visibility, nullable types, generics, and subtypes.

Also explained in

Compare how 21 books explain class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.