Câu hỏi phỏng vấn Kotlin
Câu hỏi

What is a primary constructor in Kotlin?

Câu trả lời

A primary constructor in Kotlin is a concise way to initialize a class and its properties. It is part of the class header and goes after the class name, enclosed in parentheses. The primary constructor can have parameters that are used to initialize the class properties[1][2].

Here's an example of a class with a primary constructor:

kotlin Copy
class Person(val name: String, var age: Int) {
    // class body
}

In this example, the primary constructor declares two properties: name (read-only) and age (read-write). When an object of the Person class is created, the values passed to the constructor will initialize these properties[2].

The primary constructor can also be used with initializer blocks prefixed with the init keyword. These blocks are executed when an instance of the class is created and can contain additional initialization logic[1][2].

kotli... Copy
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Why is there no static keyword in Kotlin?

junior

What is the idiomatic way to remove duplicate strings from array?

middle

What is a purpose of Companion Objects in Kotlin?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào