0
@FunctionalInterface
interface Interf {
    fun m1(num: Int)
}

fun main() {
    val a: Interf = { 34 -> println("Hello world !!") }
}

Upon compilation getting this error

Unexpected tokens (use ';' to separate expressions on the same line)

Is Kotlin lambda function syntax is bit different from Java Lambda Expression?

1 Answer 1

3

First of all, this will not compile in java as well:

@FunctionalInterface
interface Interf {
    void m1(int num);
}

class Main {
    public static void main(String[] args) {
        Interf f =  34 -> System.out.println("Hello world !!"); //compilation error here
    }
}

With pretty the same error:

error: ';' expected
        Interf f =  34 -> System.out.println("Hello world !!");
                      ^

To make it correct, name of the lambda parameter should be changed, so that it become a valid java identifier.

For instance, this will compile:

Interf f =  x -> System.out.println("Hello world !!");

Now, returning back to Kotlin. Version 1.4 introduces syntax for SAM conversions:

fun interface Interf {
    fun m1(num: Int)
}

It could be instantiated with:

val a = Interf { println("Hello world !!") }

Convention of implicitly declared it parameter referring to lambda only parameter is preserved here.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to expand on this answer and add that the reason why it's not working for Shivam is because he must use an argument e.g. x instead of 34 as in val a: Interf = { x -> println("Hello world !!") }. This is because he needs to provide an argument, not apply an argument!
Thanks @Stefan. I did the correction in the code and works fine val a = { num: Int -> println("Hello World") } a.invoke(2). Here a.invoke(int) or a(int) both can be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.