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

bookConstructors in Kotlin

Desliza para mostrar el menú

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

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 4. Capítulo 3
some-alt