What is Kotlin SAM ?

Oğuzhan Aslan
2 min readAug 24, 2022

--

Photo by Domenico Loia on Unsplash

If you ever write Kotlinbefore, you probably heard about its SAM feature or namely Functional Interfaces. The feature is used by many libraries out there, i.e Ktor. Thus, learning what it is and how to use it is a must, if not is a should, for us as developers.

Kotlin’s main strengths against java are having shorter and less crowded coding syntax. The engineers who built the Kotlin generally focus on these two points. As It can be seen easily, SAM feature also focuses on these two points.

Java or Kotlin does not matter which one you use, the callbacks have been developers headache. Especially when you start nesting them, things can get out of control easily. Additionally, when you try to create an anonymous class out of interfaces, the code gets too intended and hard to read. Also, doing it for interfaces with only one method/function requires too much effort just to provide a single function implementation. This is where SAM feature comes in to play .

without SAM feature, simple foointerface usage looks like this:

but using SAM in the same code makes it more readable. Just like this :

Even more, the feature also makes the functions that takes the SAM interface as a parameter more readable. The functions become more similar to Kotlin DSL usage. Take a look below.

To create your own SAM interface, all you have to do is add funkeyword at the very beginning and rest is just magic. However, you cannot use SAM with the interfaces that have more than 1 function. This should not be a suprize for us since SAM actually stands for single abstract method.

Additionally, SAM interfaces in kotlin supports java too which means you can call them from java code as well.

And That is it, Thank you for reading through this far. Let SAM interfaces make your day and your code better.

Linkedin

References:

https://kotlinlang.org/docs/java-interop.html#using-jni-with-kotlin

Love you all.

Stay tune for upcoming blogs.

Take care.

--

--