Introduction
Extension functions let you add new actions to existing types without changing their code.
fun ReceiverType.functionName(parameters): ReturnType { // function body }
fun String.shout() = this.uppercase() + "!"
fun Int.isEven(): Boolean { return this % 2 == 0 }
fun List<Int>.sumAll(): Int = this.sum()
fun String.shout() = this.uppercase() + "!" fun main() { val word = "hello" println(word.shout()) }
greet for the String type in Kotlin?fun ReceiverType.functionName(). Here, String is the receiver type.fun String.greet(). Other options do not follow this syntax.square for Int that returns the square of the number?fun ReceiverType.functionName(): ReturnType = expression. fun Int.square(): Int = this * this matches this.this * this and returns Int. fun Int.square() { this * this } uses braces (block body) but misses return statement, thus returns Unit. fun Int.square() = Int * Int uses invalid Int * Int.fun String.shout() = this.uppercase() + "!"
fun main() {
val word = "hello"
println(word.shout())
}shout converts the string to uppercase and adds an exclamation mark.word.shout() returns "HELLO!" which is printed.fun Int.double {
return this * 2
}double misses parentheses.this is valid in extension functions. Return statements are allowed. Extension functions can be declared for Int.isEven() to Int? (nullable Int) that returns true if the number is even, and false if it's odd or null. Which is the correct way to declare this extension function?Int? as receiver type. fun Int?.isEven(): Boolean = this != null && this % 2 == 0 does this correctly.Pass the test and this pattern moves unknown