Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a less ugly way to return function in Kotlin?

Tags:

kotlin

This declaration works, but is not the most beautiful code. Is there a way to return functions less ugly? I tried (s: String) -> writer.println(s) but this didn't work.

val writeStuff: (PrintWriter) -> (String) -> Unit = {
    val writer = it
    val f: (String) -> Unit = {
        writer.println(it)
    }
    f
}
PrintWriter("test").use { writeStuff(it)("TEST") }

EDIT: a bit more concrete example:

val writeStuff: (PrintWriter) -> (String) -> Unit = { writer ->
    { writer.println(it) }
}

val sendStuff: (Any) -> (String) -> Unit = { sender ->
    { sender.equals(it) }
}

@Test fun test1() {
    val li = listOf("a", "b", "c")

    val process: List<(String) -> Unit> = 
        listOf(writeStuff(PrintWriter("a")), sendStuff(Object()))

    process.map { li.map(it) }
}
like image 620
BasilTomato Avatar asked Feb 29 '16 19:02

BasilTomato


People also ask

Can you return a function in Kotlin?

Functions in Kotlin are declared with the fun keyword. The body of a function is called a block and is enclosed within { } curly brackets. Functions may return values with the return keyword.

What is the default return type of a function in Kotlin?

Note that we specified the return value of the function. By default, return returns from the nearest enclosing function or anonymous function.

How do you exit a function in Kotlin?

Now, by using break with a label ( break@test in this case), you can break the specific loop. Here, when i == 2 expression is evaluated to true , break@first is executed which terminates the loop marked with label first@ .


1 Answers

First, you can simplify your code using lambda syntax with explicit parameter and inlining val f:

val writeStuff: (PrintWriter) -> (String) -> Unit = { writer -> 
    { writer.println(it) } 
}

But since Kotlin supports local function declarations, you can even make writeStuff a local fun instead of a val.

This would lead to the following code:

fun writeStuff(writer: PrintWriter): (String) -> Unit {
    return { writer.println(it) }
}

Or, using the single expression syntax,

fun writeStuff(writer: PrintWriter): (String) -> Unit = { writer.println(it) }

The usage, however, will be the same:

PrintWriter("...").use { writeStuff(it)("...") }
like image 78
hotkey Avatar answered Oct 06 '22 19:10

hotkey