Rashedul Hasan
Rashedul Hasan

Reputation: 155

How to apply sam conversion to my anonymous class implementation and convert it to lambda

In java I can use anonymous class to implement an interface like below:

Interface:

interface Human
{
    void think();
}

Implementation:

public class  Runner
{
    public static void main(String[] args) 
    {
        Human programmer = new Human()
            { public void think()
                {
                    System.out.println("Hello World!");
                }

            };

            programmer.think()

    }
}

And if i convert it to kotlin then it becomes:

Interface:

interface Human
{
    fun think()
}

Implementation:

fun main(args: Array<String>)
{
    var programmer : Human = object : Human
                        {
                            override fun think()
                            {
                                System.out.println("Hello World!")  
                            }

                        }

        programmer.think()

}

But can i apply SAM(Single abstract method) conversion in the kotlin implementation and convert to lamda?

Upvotes: 0

Views: 203

Answers (1)

Enselic
Enselic

Reputation: 4912

No, you can not use SAM conversion for Kotlin interfaces, only for Java interfaces. This is explicitly pointed out by official docs on SAM conversions (emphasis mine):

[SAM conversion] works only for Java interop; since Kotlin has proper function types, automatic conversion of functions into implementations of Kotlin interfaces is unnecessary and therefore unsupported.

Upvotes: 1

Related Questions