Kotlin Extension Properties

1 minute read

Extension Properties

In Kotlin, just like extension function, properties can have extension properties too. The syntax is similar to extension functions - the extended type comes right before the function or the property name -

val String.indices: IntRange
  get() = 0 until length

print("hello".indices) // 0..4

One question that people usually confuse is whether to choose function or property. The simplest suggestion is

  • property describes state
  • function describe behavior Preferring a property over a function makes sense only if it is simple enough and improves readability.

We could also create extension properties on generic

Kotlin Style Guide recommends a function over a property if the function throws an exception.

If you are planning to make extension on generic property, it is possible. For example,

val <T> List<T>.firstOrNull: T?
  get() = if (isEmpty()) null else this[0]

If you do not wish to use generic, another way is to replace T with *. It is called star projection.

val List<*>.indices: IntRange
  get() = 0 until size

Summary

While both extension function and extension properties can do mostly the same, we should try keeping close the Style Guide by Kotlin. The basic rule of thumb is to find out if it describes a behavior or state.

There is also additional set of guidelines that help us to decide if property is preferred over function:

  • does not throw exception
  • is cheap to calculate or cached on the first run
  • returns same result on multiple invokes

Tags:

Categories:

Updated: