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

bookConstructors in Kotlin

Deslize para mostrar o 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

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 4. Capítulo 3
some-alt