Bird
Raised Fist0
Kotlinprogramming~10 mins

Function declaration syntax in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Function declaration syntax
Start
↓
Write 'fun' keyword
↓
Name the function
↓
Add parentheses ()
↓
Optional: Add parameters inside ()
↓
Optional: Specify return type after ':'
↓
Write function body inside curly braces {}
↓
Function ready to be called
↓
End
This flow shows the steps to write a Kotlin function: start with 'fun', name it, add parameters and return type if needed, then write the body.
Execution Sample
Kotlin
fun greet(name: String): String {
    return "Hello, $name!"
}
Defines a function named greet that takes a name and returns a greeting string.
Execution Table
StepActionCode PartResult
1Write function keywordfunMarks start of function declaration
2Name the functiongreetFunction named greet
3Add parameters(name: String)One parameter named name of type String
4Specify return type: StringFunction returns a String
5Write function bodyreturn "Hello, $name!"Returns greeting string with name
6Function declaredfun greet(name: String): String { ... }Function ready to be called
💡 Function declaration complete and ready for use.
Variable Tracker
VariableStartAfter Step 3After Step 5Final
nameundefinedString parameterString parameterString parameter
return valueundefinedundefined"Hello, $name!""Hello, $name!"
Key Moments - 3 Insights
Why do we write 'fun' before the function name?
In Kotlin, 'fun' tells the compiler that we are declaring a function. See execution_table step 1.
What happens if we omit the return type?
If omitted, Kotlin assumes the function returns Unit (like void). Here, return type is specified at step 4.
Why are parentheses needed even if there are no parameters?
Parentheses mark the parameter list. Even empty, they are required to define a function. See step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the function name at step 2?
Afun
Bname
Cgreet
DString
💡 Hint
Check the 'Code Part' column at step 2 in execution_table.
At which step is the return type specified?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look for ': String' in the 'Code Part' column in execution_table.
If we remove the parentheses, what part of the flow breaks?
AAdding parameters
BWriting the function body
CNaming the function
DSpecifying return type
💡 Hint
Parentheses are needed to hold parameters, see concept_flow step 'Add parentheses ()'.
Concept Snapshot
fun functionName(parameters): ReturnType {
    // function body
}

- 'fun' starts the declaration
- Name the function after 'fun'
- Parameters go inside ()
- Return type after ':' (optional)
- Body inside curly braces {}
Full Transcript
This lesson shows how to write a function in Kotlin. First, write the keyword 'fun' to start. Then give your function a name. Next, add parentheses to hold parameters. You can specify the return type after a colon. Finally, write the function body inside curly braces. The example defines a greet function that takes a name and returns a greeting string. The execution table breaks down each step of writing this function. Variables like 'name' and the return value are tracked through the steps. Common confusions include why 'fun' is needed, the role of parentheses, and the return type. The quiz checks understanding of these parts. Remember, this is the basic syntax to declare functions in Kotlin.

Practice

(1/5)
1. Which of the following is the correct way to declare a simple function named greet in Kotlin that takes no parameters and returns no value?
easy
A. function greet() { println("Hello") }
B. fun greet() { println("Hello") }
C. def greet() { println("Hello") }
D. fun greet { println("Hello") }

Solution

  1. Step 1: Identify the correct keyword for function declaration

    Kotlin uses the keyword fun to declare functions. Options using function or def are incorrect.
  2. Step 2: Check the function syntax for parameters and braces

    The function must have parentheses even if there are no parameters, so fun greet { println("Hello") } is incorrect because it misses parentheses.
  3. Final Answer:

    fun greet() { println("Hello") } -> Option B
  4. Quick Check:

    fun + name + () + body = B [OK]
Hint: Remember: Kotlin functions start with 'fun' and need parentheses [OK]
Common Mistakes:
  • Using 'function' or 'def' instead of 'fun'
  • Omitting parentheses for parameter list
  • Missing curly braces for function body
2. 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
A. fun add(a: Int, b: Int): Int { a + b }
B. fun add(a Int, b Int): Int { return a + b }
C. fun add(a: Int, b: Int) -> Int { return a + b }
D. fun add(a: Int, b: Int): Int = a + b

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]
Hint: Use colons for types and '=' for single-expression functions [OK]
Common Mistakes:
  • Omitting colons between parameter names and types
  • Using '->' instead of ':' for return type
  • Missing 'return' in block body functions
3. What is the output of the following Kotlin code?
fun multiply(x: Int, y: Int): Int {
    return x * y
}

fun main() {
    println(multiply(3, 4))
}
medium
A. 12
B. 34
C. 7
D. Error

Solution

  1. Step 1: Understand the multiply function

    The function takes two integers and returns their product using return x * y.
  2. Step 2: Calculate the function call multiply(3, 4)

    3 multiplied by 4 equals 12, so the function returns 12.
  3. Final Answer:

    12 -> Option A
  4. Quick Check:

    3 * 4 = 12 [OK]
Hint: Multiply parameters and check return value [OK]
Common Mistakes:
  • Adding instead of multiplying
  • Concatenating numbers as strings
  • Assuming syntax error due to missing expression body
4. Identify the error in the following Kotlin function declaration:
fun divide(a: Int, b: Int): Int {
    return a / b
medium
A. Missing closing brace '}'
B. Incorrect return type
C. Parameters should not have types
D. Function name is invalid

Solution

  1. Step 1: Check function syntax completeness

    The function body starts with '{' but there is no closing '}', so the code is incomplete.
  2. Step 2: Verify other syntax parts

    The return type is correct, parameters have types, and the function name is valid, so no other errors.
  3. Final Answer:

    Missing closing brace '}' -> Option A
  4. Quick Check:

    All blocks need matching braces [OK]
Hint: Count opening and closing braces carefully [OK]
Common Mistakes:
  • Forgetting to close function body with '}'
  • Misplacing colons in parameters
  • Using invalid function names
5. You want to declare a Kotlin function formatName that takes two parameters: firstName and lastName (both Strings), and returns a single String in the format "Last, First". Which of the following is the correct declaration and implementation?
hard
A. fun formatName(firstName: String, lastName: String): Int = "$lastName, $firstName"
B. fun formatName(firstName String, lastName String) = lastName + ", " + firstName
C. fun formatName(firstName: String, lastName: String): String { return "$lastName, $firstName" }
D. fun formatName(firstName: String, lastName: String): String { "$lastName, $firstName" }

Solution

  1. Step 1: Check parameter and return type syntax

    Parameters must use name: Type and return type must match. A uses : Int but returns String (type mismatch). B misses colons (firstName String invalid).
  2. Step 2: Verify function body syntax

    C has block body { "$lastName, $firstName" } without return, returns Unit not String. D correctly uses block body with return and string interpolation.
  3. Final Answer:

    fun formatName(firstName: String, lastName: String): String { return "$lastName, $firstName" } -> Option C
  4. Quick Check:

    Correct types + block body with return + interpolation = D [OK]
Hint: Use return keyword in block body functions for clarity [OK]
Common Mistakes:
  • Omitting return keyword in block body
  • Missing return type declaration
  • Incorrect string concatenation or interpolation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard