Welcome to our Kotlin tutorial on Single-Expression Functions! In this lesson, we'll explore how to write concise, easy-to-read functions using a single expression in Kotlin. Let's dive in! 🐋
Single-expression functions are functions that contain only one expression. They are useful for writing short functions that return a value without performing any additional operations.
fun square(number: Int): Int {
return number * number
}In the above example, the function square takes an Int as an argument and returns the square of the number using a single expression.
To create a single-expression function, follow these steps:
fun keyword and provide the function name, type parameters, and the return type.fun square(number: Int): Int {
// Your expression goes here
}fun square(number: Int): Int = number * numberreturn keyword.fun square(number: Int): Int {
return number * number
}Let's create a function that calculates the Fibonacci sequence up to a given number using a single-expression function.
fun fibonacciSequence(n: Int): List<Int> {
val fibSequence = mutableListOf(0, 1)
// Generate the sequence using a single-expression function
fun generateFibonacci(n: Int, current: List<Int>): List<Int> {
val next = current[current.size - 1] + current[current.size - 2]
return if (n <= 0) current else generateFibonacci(n - 1, current.toMutableList().also { it.add(next) })
}
// Call the generateFibonacci function recursively
generateFibonacci(n - 1, fibSequence)
}In this example, we define a generateFibonacci single-expression function that calculates the next number in the Fibonacci sequence using a single expression. We then call this function recursively to generate the entire sequence.
Which of the following functions is a single-expression function?
That's it for our Kotlin Single-Expression Functions tutorial! We hope you enjoyed learning and practicing with us. Stay tuned for more tutorials on Kotlin and happy coding! 🐋 💻 🎉