在Kotlin中有一种不那么难看的回归功能吗?

时间:2016-02-29 19:22:02

标签: kotlin

此声明有效,但不是最漂亮的代码。有没有办法让函数不那么难看?我试过(s: String) -> writer.println(s),但这没效果。

val writeStuff: (PrintWriter) -> (String) -> Unit = {
    val writer = it
    val f: (String) -> Unit = {
        writer.println(it)
    }
    f
}
PrintWriter("test").use { writeStuff(it)("TEST") }
编辑:更具体的例子:

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) }
}

1 个答案:

答案 0 :(得分:18)

首先,您可以使用lambda syntax使用显式参数和内联val f来简化代码:

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

但是,由于Kotlin支持local function声明,您甚至可以writeStuff成为本地fun而不是val

这将导致以下代码:

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

或者,使用single expression syntax

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

然而,用法将是相同的:

PrintWriter("...").use { writeStuff(it)("...") }