Initializing body of constructor
In the Java world, we used to initialize fields of the class in the constructor, as shown in this code:
class Student{ int roll_number; String name; Student(int roll_number,String name){ this.roll_number =roll_number; this.name = name; } }
So, if the argument's name was similar to that of the property (which was usually the case for making the code more readable), we needed to use this keyword. In this recipe, we will see how to implement the same thing in Kotlin (obviously with much less code).
Getting ready
You need an IDE to write and execute your code. I'll be using IntelliJ IDEA. We will create a Student
class with name
and roll_number
as properties.
How to do it...
Let's look at the mentioned steps to initialize a constructor:
- Kotlin provides a syntax that can initialize the properties with much less code. Here's what class initialization looks like in Kotlin:
class Student(var roll_number:Int, var name:String)
- You don't even need to define the...