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

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
I have a question

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





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Expose .niogit from Red Hat Business Central

Big O- Simple Demo And Explanation

Writing a Data Provider for MSTICPy

Fully Disable Hyper-V to turn back to vmware/virtualbox.

5 Resources for the Agile Attorney

My emoji story from 😔 ➡️ 😊

Mock Abstract Class to Test

Switching Between Fragments Without the Mindless Killing Spree

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
Suneet Agrawal

Suneet Agrawal


More from Medium

RecycleView Kotlin — Android Studio

Dependency Injection with Hilt (Kotlin)

Exploring Android 13: Programmable Shaders

Android Kotlin GraphQL Tutorial