Group Initialisation in Kotlin
Group object initialisation in Kotlin promote cleaner and easier to read code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
data class User(val name: String, var age: Int = 0, var website: String = "", val active: Boolean = true)
fun main(args: Array<String>) {
val user1 = User("Marcos Placona")
user1.age = 34
user1.website = "https://www.placona.co.uk"
println(user1)
//User(name=Marcos Placona, age=34, website=https://www.placona.co.uk, active=true)
println(User("RealKotlin").apply {
age = 1
website = "https://www.realkotlin.com"
})
//User(name=RealKotlin, age=1, website=https://www.realkotlin.com, active=true)
}
A caveat for using this type of initialisation is that all properties will end up being vars
and therefore mutable which can cause undesired behaviour.