Return Values
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 57 of 93.
Functions can do more than just perform actions - they can also send a value back to where they were called. To do this, you specify a return type after the parentheses and use the return keyword.
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
val result = add(3, 5)
println(result)
}
// Output: 8The : Int after the parentheses declares that this function returns an integer. The return statement sends the value back and immediately exits the function. The caller can then store this value in a variable or use it directly.
Return values make functions much more versatile. Instead of just printing results, functions can calculate values that you use elsewhere in your program:
fun double(n: Int): Int {
return n * 2
}
fun main() {
println(double(7) + 1)
}
// Output: 15If a function doesn't return anything meaningful, it has a return type of Unit. You can omit this type since Kotlin assumes it by default - that's why our earlier functions with just println() didn't need a return type.
Challenge
MediumWrite a function multiply that takes two integers and returns their product.
The function should multiply the two numbers together and return the result.
Parameters:
a(Int): The first numberb(Int): The second number
Returns: The product of a and b (Int)
Try it yourself
fun multiply(a: Int, b: Int): 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