0
0
Kotlinprogramming~5 mins

Function declaration syntax in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you declare a simple function in Kotlin that takes no parameters and returns no value?
Use the fun keyword followed by the function name and empty parentheses. For example: <br>
fun greet() {<br>    println("Hello!")<br>}
Click to reveal answer
beginner
What is the syntax to declare a Kotlin function that returns an integer?
Specify the return type after the parameter list with a colon. For example: <br>
fun add(a: Int, b: Int): Int {<br>    return a + b<br>}
Click to reveal answer
beginner
How do you declare a Kotlin function with parameters?
Inside the parentheses after the function name, list parameters with their names and types separated by commas. For example: <br>
fun greet(name: String) {<br>    println("Hello, $name!")<br>}
Click to reveal answer
intermediate
What is a single-expression function in Kotlin and how is it declared?
A function that returns a single expression can be declared using the = sign without curly braces. For example: <br>
fun square(x: Int): Int = x * x
Click to reveal answer
intermediate
Can Kotlin functions have default parameter values? How do you declare them?
Yes, you can assign default values to parameters in the declaration. For example: <br>
fun greet(name: String = "Guest") {<br>    println("Hello, $name!")<br>}
Click to reveal answer
Which keyword is used to declare a function in Kotlin?
Afun
Bfunction
Cdef
Dfunc
How do you specify the return type of a Kotlin function?
AInside the function body
BAfter the function name, before parentheses
CAfter the parameter list, separated by a colon
DYou cannot specify return types in Kotlin
What is the correct way to declare a function with a single expression in Kotlin?
AUse = sign followed by the expression without curly braces
BUse parentheses around the expression
CUse the keyword 'single' before fun
DUse curly braces and return statement
How do you provide a default value for a function parameter in Kotlin?
AKotlin does not support default parameter values
BUsing : after the parameter name
CInside the function body only
DUsing = after the parameter type in the declaration
Which of these is a valid Kotlin function declaration?
Adef greet() { println("Hi") }
Bfun greet() { println("Hi") }
Cfunction greet() { println("Hi") }
Dfunc greet() { println("Hi") }
Explain how to declare a Kotlin function with parameters and a return type.
Think about the order: fun, name, parameters, return type, then body.
You got /5 concepts.
    Describe what a single-expression function is in Kotlin and how to write one.
    It's a short way to write functions that return one thing.
    You got /4 concepts.