Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Automatic vs. Manual Conversion | Type Inference and Conversion
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
Kotlin Data Types

bookAutomatic vs. Manual Conversion

Sveip for å vise menyen

Kotlin takes a strict approach to type safety, which means it does not perform implicit numeric conversions between different types. In contrast to Java, where you might assign an int to a double without any explicit cast, Kotlin will not automatically convert one numeric type to another. This design choice helps prevent unexpected behavior and bugs that can result from silent type changes. If you want to convert a value from one numeric type to another in Kotlin, you must do so explicitly using conversion functions such as toDouble(), toInt(), and others.

Main.kt

Main.kt

copy
1234567891011
package com.example fun main() { val myInt: Int = 42 // Uncommenting the following line will cause a compilation error: // val myDouble: Double = myInt // Error: Type mismatch // Correct manual conversion: val myDouble: Double = myInt.toDouble() println("Converted value: $myDouble") // Output: Converted value: 42.0 }

As you saw above, trying to assign an Int directly to a Double variable causes a compilation error because Kotlin enforces explicit conversion. By requiring you to use functions like toDouble(), Kotlin ensures that every type change is intentional and visible in your code. This approach increases type safety and makes your programs more predictable, as there is no risk of accidental data loss or subtle bugs caused by implicit conversions.

question mark

What is true about numeric type conversions in Kotlin?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 2. Kapittel 4
some-alt