Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Constructors in Kotlin | Classes
Introduction to Kotlin

bookConstructors in Kotlin

Scorri per mostrare il menu

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

Main.kt

copy
12345678910111213
package 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.

question mark

Which statement about primary constructors in Kotlin is correct?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 4. Capitolo 3
some-alt