Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

In this lesson you will learn the basics of type conversion in Kotlin so you can move between strings and numbers. This is for anyone searching for "Kotlin toInt toString how to use".

Type conversion (casting) - string to number, number to string - is a fundamental programming operation. You use .toInt() and .toString().

The sample code turns the string "123" into an integer with "123".toInt() and uses it in arithmetic, then turns the number 45 into a string with n.toString(). In Kotlin the conversion methods live on the value itself.

A common stumbling block for beginners is not allowing for conversion failure. Calling .toInt() on a string that is not a number throws, so .toIntOrNull() handles it more safely.

In real-world development, conversion happens daily - turning what a user typed into a form into a number for a calculation, or turning a result back into a string for display.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)