Can I get an example of a practical world use of: ...
# announcements
b
Can I get an example of a practical world use of: https://jorgecastillo.dev/kotlin-sam-conversions
j
Typical callback, for example, if a textview was written in kotlin instead of java, you could not do
textView.setOnClickListener{ ... }
You should use the object : Listener { ... }
With SAM you can avoid to write this object and just write the lamba directly
b
Sorry that's still not clear for me. What stops you from having fun TextView.setOnClickListener(f: (event: Event)->Unit) in your interface? (and it can add to an internal list for example)
n
Will then it's a bit of the opposite, it would make writing an out of line class more awkward
The idea I think is just to be able to have API that is suitable both for convenient inline use and defining more formal out of line classes as well
r
Avoiding boxing is a bonus
p
With SAM you can create a common method whose operations can be defined later on for eg fun interface MathOperation { fun operation (num1: Int, num2: Int): Int } //Call like this val add = MathOperation {num1, num2 -> num1 + num2} add.operation(10,20) // 30 val multiply = MathOperation {num1, num2 -> num1 * num2} multiply.operation(10,20) //200 This can also be used to check network also, in short it's a great way to avoid excessive usage of higher order function. Here is a short tutorial which I have added on my YouTube channel which I created this week 😃 https://www.youtube.com/channel/UC6Cd6oKTujZ1kGw2DpLmYng
t
kotlin is a bit of a bridge between OOP and FP, in the sense that functions are first class citizen in kotlin. so you can write, as you did,
(Event) -> Unit
and pass it around. but that is awkward for people trained in OOP (or at least, I think, it took a while to get used to that more FP syntax and I still prefer the more OOP approach) used to have interface to achieve the same. Depending on your domain, working with interfaces makes your code more consistent, for instance I mostly deal with Spring, everything is interface there, so I prefer to use interfaces myself to be more consistent across an application (though
typealias
could bridge the gap, but that is a thought for another day). all in all I guess the point is to help adoption, now you don’t need to distinguish between java or kotlin interface, SAM supports both
a
SAM was introduced for kotlin library authors who intend to write Java libs using kotlin.