Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Constructors in Kotlin | Classes
Introduction to Kotlin

bookConstructors in Kotlin

Свайпніть щоб показати меню

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

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 4. Розділ 3
some-alt