Java SAM support in Kotlin
It is really easy to use higher-order functions in Kotlin. The problem is that we often need to interoperate with Java, which natively doesn't support it. It achieves substitution by using interfaces with only one method. This kind of interface is called a Single Abstract Method (SAM) or functional interface. The best example, of situation in which we need to set up a function this way is when we useĀ setOnClickListener
on a View
element. In Java (until 8), there was no simpler way than by using an anonymous inner class:
//Java button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Operation } });
In the preceding example, the OnClickListener
method is the SAM, because it contains only a single method, onClick
. While SAMs are very often used as a replacement for function definitions, Kotlin also generates a constructor for them that contains the function type as a parameter. It is...