When can I lower the return type in Kotlin

I have the following function in Kotlin:

fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}

which can be simplified:

fun max(a: Int, b: Int) = if (a > b) a else b

in the previous definition, the return type of the function was omitted, and this is known as the body of the expression. I am wondering if there are other cases in which you can omit the return type of the function in Kotlin.

+4
source share
3 answers

Functions with a block block must always explicitly indicate the types of data returned, unless they are intended to return Unit.

If the function does not return any useful value, its return type Unit. Unit- a type with one value is one. This value does not have to be returned.

fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello ${name}")
    else
        println("Hi there!")
    // `return Unit` or `return` is optional
}

Unit return type .

fun printHello(name: String?) {
    ...
}
+2

Unit

fun printHello(): Unit {
    print("hello")
}

fun printHello() {
    print("hello")
}

fun printHello() = print("hello")
+1

Usually a function should declare it as a return type. But if some functions consist of a single expression, we can omit the curly braces and return type and use the character =before the expression, and not with the return keyword. This type of function is called Single Expression Functions .

Example:

fun add(a: Int, b: Int): Int {
    return a + b
}

This code can be simplified to:

fun add(a: Int, b: Int) = a + b

The compiler will oblige you to do this.

+1
source

Source: https://habr.com/ru/post/1677626/


All Articles