The init
block in Kotlin is used to initialize properties and execute code when an object is created. It's part of the class's primary constructor and allows you to execute code as soon as the object is instantiated.
Let's dive into how and when you can use the init
block in Kotlin!
The init
block is used for initialization code. It runs immediately when an object of the class is created, and it's the place to perform any setup you need that isn't part of the constructor's parameter initialization.
// Example of using init block class Student(val name: String, var grade: Int) { init { // Code inside init block is executed when the object is created println("Student Created: Name = $name, Grade = $grade") } } // Creating an object of Student val student1 = Student("John", 90)
In this example, when the Student object is created, the init
block is executed, printing the details of the student.
In Kotlin, you can have multiple init
blocks in a class. These blocks will be executed in the order they are defined.
// Multiple init blocks class Book(val title: String, val author: String) { init { println("Initializing Book: $title by $author") } init { println("Book Initialized: $title") } } // Creating an object of Book val book1 = Book("Kotlin Programming", "Jane Smith")
Here, we have two init
blocks in the Book class. The output will print the initialization message twice, in the order the blocks appear.
The init
block is a good place to validate or modify the properties of an object when it's created.
// Using init block for validation class Account(val accountNumber: String, var balance: Double) { init { if (balance < 0) { balance = 0.0 println("Negative balance is not allowed. Setting balance to 0.") } } } // Creating an object of Account val account1 = Account("12345", -500.0) println("Account Balance: ${account1.balance}")
In this case, the init
block checks whether the balance is negative. If it is, it sets the balance to 0 and prints a message.
Since the init
block runs when the object is created, you can access constructor parameters directly within the block to perform additional initialization tasks.
// Accessing constructor parameters in init block class Product(val name: String, var price: Double) { init { println("Product Initialized: $name, Price: $price") } fun applyDiscount(discount: Double) { price -= price * (discount / 100) } } // Creating a Product object val product1 = Product("Smartphone", 799.99) product1.applyDiscount(10) println("Price after discount: ${product1.price}")
The init
block prints the initial product details when the object is created. After that, you can apply a discount using the applyDiscount
method, which modifies the price.
Try these challenges to get hands-on experience with the init
block:
init
block to set a minimum salary (e.g., $1000) if the provided salary is too low.init
block, calculate the area and perimeter of the rectangle.init
block, ensure that the year is a valid, non-negative number, and if it's not, set it to the current year.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!