Type Conversion
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 38 of 93.
Since readLine() returns a nullable string (null at end of input), you'll need to convert that input when you want to work with numbers. Kotlin provides conversion functions to transform strings into other types.
To convert a string to an integer, use toInt():
fun main() {
val input = readLine()!!
val number = input.toInt()
println(number + 10)
}If the user enters "5", the program converts it to the integer 5, then adds 10 to get 15. Without conversion, "5" + 10 concatenates text and produces "510". Converting first gives numeric addition.
For decimal numbers, use toDouble():
fun main() {
val price = readLine()!!.toDouble()
println("With tax: ${price * 1.1}")
}You can chain the conversion directly after readLine()!! for cleaner code. Other useful conversions include toLong() for large integers and toBoolean() for boolean values.
These conversions assume the input is valid. If someone enters "hello" when you expect a number, the program will crash. You'll learn to handle such errors later in the course.
Challenge
EasyWrite a function calculateFutureAge that takes currentAge and yearsToAdd as strings and returns the future age as an integer.
Convert both string parameters to integers, add them together, and return the result.
Parameters:
currentAge(String): The current age as a string (e.g., "25")yearsToAdd(String): The number of years to add as a string (e.g., "10")
Returns: The sum of both values as an integer (Int)
Try it yourself
fun calculateFutureAge(currentAge: String, yearsToAdd: String): Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground