A Discussion On How Kotlin Extension Functions Can Be Used

fun String.validateEmail(): Boolean {
//validation process
return result
}
class EmailValidator {
fun validate(email: String): Boolean {
//validation process
return result
}
}
fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R = ....class ArrayList {
@Override
public void forEach(Consumer<? super E> action) {...}
}
class Refrigerator {
fun start() {}
fun stop() {}
}
class RefrigeratorBeerScope {
fun Refrigerator.adjustSuitableTemperatureForYeast() {
//...
}
}
class Application {
fun main() {
//In this section, the refrigerator works traditionally
val refrigerator = Refrigerator()
refrigerator.start()
refrigerator.stop()
with (RefrigeratorBeerScope()) {
//At this point, the refrigerator is now working for yeast fermentation.
refrigerator.adjustSuitableTemperatureForYeast()
}
//RefrigeratorBeerScope is ends, and adjustTemperatureToKeepYeastSuitableTemperature extension function cannot be called any longer.
refrigerator.adjustTemperatureToKeepYeastSuitableTemperature()//this code cannot be compiled
}
}
class CollectionIterationScope {
fun <E> List<E>.forEach(consumer: Consumer<E>) { ... }
fun <E> List<E>.iterator(): Iterator<E> { ... } fun <E> Set<E>.forEach(consumer: Consumer<E>) { ... }
...
}
...
val list = ArrayList()
with(CollectionIterationScope()) {
list.forEach { ... }
...
}
...
class CreditCardUtil {
fun getCreditCardType(creditCardNumber: String): CreditCardType
fun isCardNumberValid(creditCardNumber: String): Boolean
...
}
or could beclass StringCreditCardNumberScope {
fun String.getCreditCardType(): CreditCardType
fun String.isValidCardNumber(): Boolean
....
}
fun addEmail() {
val emails = mutableListOf<String>()
with(MutableCollectionAsyncScope()) {
emails.asyncAdd("")
}
}
class MutableCollectionAsyncScope {
fun <E> MutableCollection<E>.asyncAdd(element: E) {
Executors.newSingleThreadExecutor().execute {
add(element)
}
}
}

--

--

--

Senior Android Developer

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

Recommended from Medium

Git bisect: The unsung hero for hunting down bugs

Inference data mid project

November Porto Tech & Creative Events

Neo4j and GraphQL Heavenly Match #1 — Directional Relationships

Raise your hand if you want to quit drinking coffee. Why, though???

CONTENTS LIST

What to do about BigQuery error “Resources exceeded during query execution”

Ordeals of a small exporter in India. Part 2

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
Güneş Maboçoğlu

Güneş Maboçoğlu

Senior Android Developer

More from Medium

(번역) Let’s talk about how okhttp implements websocket

Mustache, rendering and localitazion email in Kotlin

Kotlin Native (Server side development)

Object Oriented Programming in Kotlin [OOP in Kotlin — 2022]