CodeBlanks Logo Icon CodeBlanks

Extension properties

Learn extension properties with val Receiver.ext.

Extension property

An extension property adds a property to an existing type from outside. It is written as val Receiver.prop: Type and uses a getter.

Example: val String.isLong: Boolean get() = length > 10. This adds isLong to String. Calling "hello world".isLong returns true. Extension properties can only have a getter, because an extension cannot store a backing field. They suit computed values.

The isLong property

The getter of an extension property accesses the receiver's methods and properties through this. Because there is no backing field, only computation runs.

Example: val String.isLong: Boolean get() = length > 10. Here length means this.length. Calling "hello world".isLong returns true; "short" gives false. An extension property is a short way to add a computed property without changing the class source.

Practice The String.isLong extension property

Define an extension property val String.isLong: Boolean whose getter returns length > 10. In main print "hello world".isLong and "short".isLong on separate lines with println.

Starter code

Main.kt
// Define the String.isLong extension property
// getter returns length > 10
// print both values in main

Sample solution

Main.kt
val String.isLong: Boolean
    get() = length > 10

fun main() {
    println("hello world".isLong)
    println("short".isLong)
}

Expected output

true
false

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the extension property parts

Term Meaning
val String.isLong Receiver and property
get() = length > 10 Getter body
"abc".isLong Call
Boolean Return type

2 Why can an <strong>extension property</strong> only be val (not var)?

  • Because val is faster
  • Because it cannot store a backing field Correct answer
  • Because var syntax is invalid
  • Because it is only declared inside a class

Explanation: An extension property cannot store a backing field; that is why it is val only.

3 Complete the extension property definition

Question
val String.isLong: Boolean
    get() = ____ > 10
Answer
val String.isLong: Boolean
    get() = length > 10

Explanation: length returns the String length.

All lessons in Intermediate