Initialize an object in Kotlin
This article explores different ways to initialize an object in Kotlin.
1. Using Class Constructor
The standard way to initialize an object in Kotlin is with the class constructor. It can accept a set of parameters to initialize its fields, or it can be parameterless. Kotlin has a concise syntax for declaring properties and initializing them:
|
1 2 3 4 5 6 |
data class Person(var name: String? = null, var age: Int = 0) fun main() { val person = Person("John", 22) println(person) } |
2. Using Copy Constructor
The copy constructor is a special constructor for creating a new object from another object. It takes a single argument, which should be another instance of the same class. You can explicitly invoke another constructor within the copy constructor with the this() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
data class Person(var name: String, var age: Int) { // Copy Constructor constructor(person: Person) : this(person.name, person.age) } fun main() { val oldUser = Person("John", 22) val newUser = Person(oldUser) println(newUser) } |
3. Properties
Another alternative is to get an instance of the class using the default constructor and set its properties later.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
internal class Person() { var name: String? = null var age: Int = 0 override fun toString(): String { return listOf(name, age).toString() } } fun main() { val person = Person() person.name = "John" person.age = 22 println(person) } |
4. Using Anonymous Inner class
Although not recommended, you can use “Double Brace Initialization” to initialize the object. This creates an anonymous inner class with just an instance initializer in it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
internal open class Person(var name: String? = null, var age: Int = 0) { override fun toString(): String { return listOf(name, age).toString() } } fun main() { // Anonymous Class val person = object : Person() { init { // Initializer Block name = "John" age = 22 } } println(person) } |
That’s all about initializing an object in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)