Tutorial by Examples

Top-level extension methods are not contained within a class. fun IntArray.addTo(dest: IntArray) { for (i in 0 .. size - 1) { dest[i] += this[i] } } Above an extension method is defined for the type IntArray. Note that the object for which the extension method is defined (cal...
The extension method to be called is determined at compile-time based on the reference-type of the variable being accessed. It doesn't matter what the variable's type is at runtime, the same extension method will always be called. open class Super class Sub : Super() fun Super.myExtension()...
Given any value of type Int or Long to render a human readable string: fun Long.humanReadable(): String { if (this <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB", "EB") val digitGroups = (Mat...
A common use case for extension methods is to improve an existing API. Here are examples of adding exist, notExists and deleteRecursively to the Java 7+ Path class: fun Path.exists(): Boolean = Files.exists(this) fun Path.notExists(): Boolean = !this.exists() fun Path.deleteRecursively(): Bool...
In Kotlin you could write code like: val x: Path = Paths.get("dirName").apply { if (Files.notExists(this)) throw IllegalStateException("The important file does not exist") } But the use of apply is not that clear as to your intent. Sometimes it is clearer to create a ...
With this declaration: fun Temporal.toIsoString(): String = DateTimeFormatter.ISO_INSTANT.format(this) You can now simply: val dateAsString = someInstant.toIsoString()
If you want to extend a class as-if you are a static function, for example for class Something add static looking function fromString, this can only work if the class has a companion object and that the extension function has been declared upon the companion object: class Something { compani...
Assume you want to create an extension property that is expensive to compute. Thus you would like to cache the computation, by using the lazy property delegate and refer to current instance (this), but you cannot do it, as explained in the Kotlin issues KT-9686 and KT-13053. However, there is an off...
You can use extensions for reference View, no more boilerplate after you created the views. Original Idea is by Anko Library Extensions inline fun <reified T : View> View.find(id: Int): T = findViewById(id) as T inline fun <reified T : View> Activity.find(id: Int): T = findViewById(i...

Page 1 of 1