Constructors and init
Create and initialize objects.
What Is a Constructor?
A constructor is special code that runs when you create an object. It sets up the object's starting values.
In Kotlin the main constructor is written right next to the class name.
The Primary Constructor
The primary constructor goes in parentheses after the class name. You pass values when creating the object.
Here Dog requires a name when constructed.
class Dog(name: String) {
val dogName = name
}
fun main() {
val d = Dog("Rex")
println(d.dogName)
}All lessons in this course
- Declaring Functions
- Classes and Properties
- Constructors and init
- Data Classes