Kotlin "did not expect any parameters" when trying to return the built-in lambda

I am trying to write a Kotlin function that returns lambda with a parameter. I am trying to use the following code for this:

fun <T> makeFunc() : (T.() -> Unit) {
    return { t: T ->
        print("Foo")
    }
}

Note. In a real program, the function is more complex and uses t.

Kotlin rejects this as invalid, giving the error "Expected Without Parameters" in t: T.

However, assigning this lambda to a variable at first is not rejected and works fine:

fun <T> makeFunc() : (T.() -> Unit) {
    val x = { t: T ->
        print("Foo")
    }

    return x
}

These two fragments seem the same, so why is this so? Are the braces after the statement returninterpreted as something other than lambda?

In addition, IntelliJ tells me that the value of a variable may be nested, while this causes an error.

enter image description here

+4
2

-.

, :

  • (A, B) -> C , A.(B) -> C. .

    , , (T) -> Unit, , T.() -> Unit, .

  • -, , .

    T.() -> Unit, T , ,

    literal . , , . , , as.

    ( )

    lambdas: . , it, .

:

fun foo(bar: (A) -> B) = Unit
fun baz(qux: A.() -> B) = Unit

val f: (A) -> B = { TODO() }
val g: A.() -> B = { TODO() }

foo(f) // OK
foo(g) // OK
baz(f) // OK
baz(g) // OK

// But: 

foo { a: A -> println(a); TODO() } // OK
foo { println(this@foo); TODO() } // Error

baz { println(this@baz); TODO() } // OK
baz { a: A -> println(a); TODO() } // Error

, IDE, . , Kotlin.

+5

() -> Unit T, , . "()". . T , T this:

fun <T> makeFunc(): (T.() -> Unit) {
    return {
       print(this)
    }
}
+1

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


All Articles