This article explores different ways to convert a string to all other data types supported by Kotlin.

1. Convert String to Int

You can use the toInt() function to get the corresponding int value of a string. If the string is not a valid representation of a number, NumberFormatException would be thrown.

2. Convert String to Float

You can use the toFloat() function to get the corresponding float value from a String. If it cannot convert the string to a float, NumberFormatException will be thrown.

3. Convert String to Double

You can use the toDouble() function to get the corresponding double value. If it cannot convert the string to a double, NumberFormatException will be thrown.

4. Convert String to Long

You can use the toLong() function to parse the string as a long number. If the string is not a number, NumberFormatException will be thrown.

5. Convert String to Short

You can use the toShort() function to get the corresponding short value. If it cannot convert the string to a short, NumberFormatException will be thrown.

6. Convert String to Boolean

You can use the toBoolean() to get the Boolean value represented by the specified string. The function returns true if the specified string is equal to “true” (case ignored) and false otherwise.

7. Convert String to Character Array

To convert a string to a character array containing the characters in the string, you can use the toCharArray() function.

8. Convert String to Byte Array

To convert a string to a byte array, you can use the getBytes() function, which encodes the string’s contents into a sequence of bytes using default or specified encoding.

9. Convert String to Byte

You can parse a string as a signed Byte number using the toByte() function. It throws NumberFormatException if the string is not a valid representation of a number.

10. Convert String to BigDecimal

Finally, you can also convert a string to a BigDecimal using the toBigDecimal() function. It throws NumberFormatException if the string is not a valid representation of a number.

That’s all about conversion between a string and other data types in Kotlin.