Bird
0
0

Which of the following is the correct syntax to declare a function add that takes two Int parameters and returns their sum as an Int?

easy📝 Syntax Q12 of 15
Kotlin - Functions
Which of the following is the correct syntax to declare a function add that takes two Int parameters and returns their sum as an Int?
Afun add(a: Int, b: Int): Int { a + b }
Bfun add(a Int, b Int): Int { return a + b }
Cfun add(a: Int, b: Int) -> Int { return a + b }
Dfun add(a: Int, b: Int): Int = a + b
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter declaration syntax

    Parameters must be declared as name: Type, so fun add(a Int, b Int): Int { return a + b } is incorrect because it misses colons.
  2. Step 2: Verify return type and function body syntax

    fun add(a: Int, b: Int): Int = a + b uses the correct syntax with an expression body and return type. fun add(a: Int, b: Int) -> Int { return a + b } uses '->' which is invalid in Kotlin. fun add(a: Int, b: Int): Int { a + b } misses the return keyword in a block body, so it won't return the sum.
  3. Final Answer:

    fun add(a: Int, b: Int): Int = a + b -> Option D
  4. Quick Check:

    fun + parameters with colons + : ReturnType + = expression = A [OK]
Quick Trick: Use colons for types and '=' for single-expression functions [OK]
Common Mistakes:
MISTAKES
  • Omitting colons between parameter names and types
  • Using '->' instead of ':' for return type
  • Missing 'return' in block body functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes