w3resource

Kotlin Function: Add two numbers with an explicit return type


Write a Kotlin function that takes two numbers as arguments and returns their sum. Explicitly specify the return type.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax: Familiarity with writing and running Kotlin programs.
  • Kotlin Functions: Understanding how to define and call functions in Kotlin.
  • Explicit Return Types: Knowledge of specifying return types for functions in Kotlin.
  • Arithmetic Operations: Ability to perform addition using the + operator.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Calculate the Sum.
  • Call the Function.
  • Display the Output.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting explicit return type.
    • Misplacing addition logic.
    • Not testing edge cases.

Sample Solution:

Kotlin Code:

fun calculateSum(num1: Int, num2: Int): Int {
    return num1 + num2
}

fun main() {
    val sum = calculateSum(7, 9)
    println("Sum: $sum")
}

Sample Output:

Sum: 16

Explanation:

In the above exercise -

  • The "calculateSum()" function takes two parameters num1 and num2, both of type Int. Inside the function, it calculates the sum of the two numbers by adding them together.
  • The function's return type is explicitly specified as Int. After addition, the function returns the sum as an integer value.
  • In the main function, we call the calculateSum function with arguments 7 and 9. The returned sum is stored in the sum variable. Finally, we print the sum value using println().

Kotlin Editor:


Previous: Print asterisk pattern.
Next: Check Prime Number, Return Boolean.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.