Type conversion (also called as Type casting) refers to changing the entity of one data type variable into another data type.
As we know Java supports implicit type conversion from smaller to larger data type. An integer value can be assigned to long data type.
var myNumber = 100 var myLongNumber: Long = myNumber // Compiles Successfully
But, Kotlin does not support implicit type conversion. An integer value can not be assigned to long data type.
var myNumber = 100 var myLongNumber: Long = myNumber // Compiler error // Type mismatch: inferred type is Int but Long was expected
In Kotlin, helper function can be used to explicitly convert one data type to another to another data type.
var myNumber = 100 var myLongNumber: Long = myNumber.toLong() // compiles successfully
The following helper function can be used to convert one data type into another:
Note: There is No helper function available to convert into boolean type.
Conversion from larger to smaller data type –
var myLongNumber = 10L var myNumber2: Int = myLongNumber1.toInt()
Kotlin Program to convert the one data type into another:
259 to byte: 3 50000 to short: -15536 21474847499 to Int: 11019 10L to Int: 10 22.54 to Int: 22 22 to float: 22.0 65 to char: A A to Int: 65
- Kotlin Data Types
- Hello World program in Kotlin
- Destructuring Declarations in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
- Kotlin Operators
- Kotlin Standard Input/Output
- Kotlin Expression, Statement and Block
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.