Junior — Middle
Is it possible to declare properties outside the class definition in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, properties are usually declared inside 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 original 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 output 'A'
}
Important: Extension properties cannot have backing fields, so they must be computed (only with a getter or with a getter and setter, but without a field).
Thus, properties can be declared outside the class definition through extensions, but with these limitations.