Search code examples
kotlinfunctional-interface

Implementing Function Interface using Lambda Expression in Kotlin


@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?


Solution

  • 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.