Making toasts with Kotlin and extension functions
With Kotlin extension functions it’s possible to display toasts as simple as this:
"This is my string".toast(context)
You’ll just need to define this extension function somewhere in your code:
fun Any.toast(context: Context, duration: Int = Toast.LENGTH_SHORT): Toast {
return Toast.makeText(context, this.toString(), duration).apply { show() }
}
This solution especially shines when combined this with Kotlin’s string templates feature:
"click on ${position.name}".toast(context)
Look at the beauty of that!
For comparison, this is how you write the same code with Java:
String message = String.format("click on %d", position.name);
Toast.makeText(context, message, Toast.LENGTH_LONG).show()