Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Explicit Type Declaration | Type Inference and Conversion
Kotlin Data Types

bookExplicit Type Declaration

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

Kotlin usually infers the type of a variable from its initializer, letting you write concise code. However, there are important reasons to use explicit type declarations. Declaring types explicitly can make code clearer, especially for other developers who may not know what type a variable should be. This practice also helps prevent errors when the initializer's type is not obvious, or when you want to avoid accidental type changes in the future. Explicit types are particularly helpful in complex codebases, when working with APIs, or when you want to ensure a variable has a specific type for consistency.

Main.kt

Main.kt

copy

Looking at the code above, you see both inferred and explicit type declarations. When you write val inferredInt = 42, Kotlin understands the type is Int from the value. But with val explicitInt: Int = 42, you make the type clear for anyone reading the code. This is especially useful if the initializer is not a simple literal, or if you want to ensure the variable stays an Int even if the initializer changes later. Declaring val longNumber: Long = 42 is a good example—without the explicit type, Kotlin would make number an Int, but you might need a Long for compatibility or to avoid overflow. In larger codebases, or when maintaining code with multiple contributors, explicit types reduce confusion and help prevent subtle bugs.

question mark

Why might you choose to declare a variable's type explicitly in Kotlin?

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

すべて明確でしたか?

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

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

セクション 2.  2

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 2.  2
some-alt