Extension properties in Kotlin
Level 5374 keystrokes
Extension properties add computed properties to existing types such as String and List<Int>. They have no backing field, so each value is calculated in get() whenever the property is read.
Kotlin code
// Extension property on String; it needs a getter because there is no backing field1val String.wordCount: Int // Split on spaces and ignore empty parts, so repeated spaces do not count as words2 get() = this.split(" ").filter { it.isNotEmpty() }.size3 // Extension property on List<Int> only4val List<Int>.average: Double // Return 0.0 for an empty list to avoid dividing by zero; toDouble() avoids integer division5 get() = if (isEmpty()) 0.0 else sum().toDouble() / size6 // Extension property that checks for a palindrome7val String.isPalindrome: Boolean // True when the string reads the same backwards8 get() = this == this.reversed()9 // Read like a normal property, without (): prints 310println("Hello World Kotlin".wordCount)// 15 / 5 = 3.011println(listOf(1, 2, 3, 4, 5).average)// "radar" reversed is the same: prints true12println("radar".isPalindrome)// "olleh" is different: prints false13println("hello".isPalindrome)Output
3 3.0 true false
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 15)× 15.× 14"× 8=× 5,× 4:× 3{× 1}× 1/× 1