- Published on
Lambda and SAM Conversion in Kotlin - Part 2
- Authors
- Name
- Esa Firman
- @esafirm
This is a article is part of the series: Lambda and SAM Conversion in Kotlin
Previous: Part 1
So we already create Interface
in Java and convert it to lambda with in Kotlin through SAM conversion. How about interface
in Kotlin? As the previous part suggest, currently there's no SAM conversion in Kotlin interface.
While Kotlin community really wanted it, i don't think we don't need a SAM conversion for Kotlin interface
.
The reason behind this is because Kotlin has proper function types which render SAM-conversions unnecessary for Kotlin as quoted from here.
So how we solve the boilerplate thingy? Simple, use Kotlin function types with typealias
!
So instead creating an intereface
for some click listener:
interface OnClickListener {
fun onClick(view: View)
}
class View {
fun setListerner(listener: OnClickListener){...}
}
You can create a function type with type alias
typealias OnClickListener = (View) -> Unit
class View {
fun setListener(listener: OnClickListener){...}
}
So you can have your nice lambda again!
// with interface
View().setOnClickListener(object: OnClickListener {
override fun onClick(view: View){
....
}
}
// with typealias
View().setOnClickListener { ... }
Until next time, cao ~ \ud83d\udcda