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 field
1val String.wordCount: Int
// Split on spaces and ignore empty parts, so repeated spaces do not count as words
2 get() = this.split(" ").filter { it.isNotEmpty() }.size
3
// Extension property on List<Int> only
4val List<Int>.average: Double
// Return 0.0 for an empty list to avoid dividing by zero; toDouble() avoids integer division
5 get() = if (isEmpty()) 0.0 else sum().toDouble() / size
6
// Extension property that checks for a palindrome
7val String.isPalindrome: Boolean
// True when the string reads the same backwards
8 get() = this == this.reversed()
9
// Read like a normal property, without (): prints 3
10println("Hello World Kotlin".wordCount)
// 15 / 5 = 3.0
11println(listOf(1, 2, 3, 4, 5).average)
// "radar" reversed is the same: prints true
12println("radar".isPalindrome)
// "olleh" is different: prints false
13println("hello".isPalindrome)

Output

3
3.0
true
false
Practice typing this code

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

More Kotlin examples at level 5

← Kotlin typing practice