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

bookType Conversion Basics

Glissez pour afficher le menu

Type conversion is a key feature in Kotlin that lets you change a value from one data type to another. You often need to convert between types like Int, Double, and String when working with user input, calculations, or displaying results. Kotlin does not perform implicit conversions between numeric types, so you must use explicit conversion functions. There are both safe and unsafe conversions. Safe conversions handle errors gracefully, while unsafe conversions can throw exceptions if the value cannot be converted.

Main.kt

Main.kt

copy
1234567891011121314151617181920212223242526
package com.example; fun main() { // Convert Int to Double val intVal: Int = 42 val doubleVal: Double = intVal.toDouble() println("Int to Double: $doubleVal") // Convert Double to Int val doubleNumber: Double = 3.1415 val intNumber: Int = doubleNumber.toInt() println("Double to Int: $intNumber") // Convert Int to String val intAsString: String = intVal.toString() println("Int to String: $intAsString") // Convert String to Int (safe) val stringNumber: String = "123" val convertedInt: Int = stringNumber.toInt() println("String to Int: $convertedInt") // Unsafe conversion: This will throw an exception // val badString: String = "abc" // val errorInt: Int = badString.toInt() // Throws NumberFormatException }

In the code above, you used several built-in conversion functions. The toDouble() function converts an Int to a Double, and toInt() converts a Double to an Int, dropping any decimal part. To convert an Int to a String, you used toString(). Converting a String to an Int is done with toInt(). However, if the string does not represent a valid integer, toInt() throws a NumberFormatException. This is an unsafe conversion. Always ensure the string contains only numeric characters before converting, or use safer alternatives like toIntOrNull() to avoid exceptions.

question mark

Which function would you use to convert a String to an Int in Kotlin?

Select the correct answer

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 3

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 2. Chapitre 3
some-alt