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

A day with Git

Spark for BI & Analytics: Databricks vs Azure Synapse Analytics

How Selenium interacts with the codes we wrote and browsers?


Improve Your Python Debugging Skills Without Effort

A Tour of Cloud Computing: “Every Enterprise Should Run on Hybrid Cloud”

A Simple Recipe App Interface with Flutter

Hacking HY-in portal

Modularized code in Solidity

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

Security in Android 12 — For Developers

Automated Gradle Publish with GitHub Actions (To Maven Central)

Null Safety in Kotlin

Jetpack Compose Basics