Sobes.tech
Junior — Middle

Kas on võimalus deklareerida omadusi väljaspool klassi määratlust Kotlinis?

sobes.tech AI

Vastus AI-lt

In Kotlin, properties are usually declared within the class definition. However, if you need to add a property outside the class, you can use extension properties.

Extensions allow you to add new properties or functions to existing classes without modifying their source code.

Example of an extension property outside the class:

class User(val name: String)

// Extension property outside the class
val User.firstChar: Char
    get() = this.name.first()

fun main() {
    val user = User("Anna")
    println(user.firstChar) // Will print 'A'
}

Important: extension properties cannot have state (backing field), so they must be computed (only with a getter or with a getter and setter, but without a field).

This way, properties can be declared outside the class definition via extensions, but with limitations.