Extensions in Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/extensions-in-kotlin/ and reposted on Medium on 20th Jul 2018.
Nice !!!

Extension Functions

To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended or the class name.

fun <T> List<T>.midElement(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[size / 2]
}

//to call this method
var list = listOf<Int>(1, 2, 3, 4, 5)
var mid = list.midElement()
//or var arrayList = arrayListOf(5, 4, 3, 2, 1)
var mid = arrayList.midElement()
Toast.makeText(this, “Hello”, Toast.LENGTH_SHORT).show()
fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}
//to call this method from any context extending class
showToast("Hello")
I have a question

Please continue reading at https://agrawalsuneet.github.io/blogs/extensions-in-kotlin/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store