Constructors in Kotlin
Sveip for å vise menyen
In Kotlin, constructors provide a way to initialize new objects and set up their properties. The most common form is the primary constructor, which is defined in the class header and allows you to declare and initialize properties in a concise way. When you create a class with a primary constructor, you can pass values directly when creating an object, ensuring that all required data is provided up front. This approach improves readability and reduces boilerplate code compared to traditional Java constructors.
Main.kt
12345678910111213package com.example class Person(val name: String, val age: Int) { fun introduce() { println("Hello, my name is $name and I am $age years old.") } } fun main() { val person = Person("Alice", 30) person.introduce() }
In this code, the Person class uses a primary constructor to declare two properties: name and age. These properties are initialized directly from the constructor parameters. When you create a new Person object using Person("Alice", 30), the values "Alice" and 30 are passed to the constructor, automatically setting the name and age properties. The introduce method then uses these properties to print a message. This demonstrates how primary constructors make property initialization straightforward and help keep your code clean and expressive.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår