Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Primary Constructors | Constructors and Methods
Kotlin Classes and Objects

bookPrimary Constructors

メニューを表示するにはスワイプしてください

Introduction to constructors

When you create a class in Kotlin, you often need a way to set up its initial state. This is where constructors come in. Constructors allow you to provide values when you create an object, ensuring that all necessary properties are initialized.

What is a Constructor?

A constructor is a special function that runs when you create an instance of a class. Its main job is to set up the object's properties with initial values. In Kotlin, you can define constructors directly in the class header or inside the class body.

Primary Constructor Syntax

The primary constructor is the main way to declare and initialize properties for a class in Kotlin. You define it in the class header, right after the class name, using parentheses. The parameters you add here can be used to initialize properties, making your class concise and readable.

User.kt

User.kt

copy

In the User class above, the primary constructor takes two parameters: name and age. By declaring them with val, you automatically create read-only properties for each parameter. When you create a new User object with User("Alice", 30), the primary constructor assigns "Alice" to name and 30 to age. This approach makes it easy to ensure that every User object has its essential properties initialized from the start.

question mark

What is the purpose of a primary constructor in Kotlin?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  1
some-alt