Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Extensions

Kotlin Extensions

Kotlin can add new functions and properties to a class without modifying the original class, using inheritance, or applying the decorator pattern.

This capability is called an extension. It lets code call the functions you add as if they were members, which reads very naturally.

But extensions are essentially just static syntactic sugar; they do not actually insert any members into the extended class. Understanding this is the key to mastering extensions.


Extension functions

An extension function is written by putting the receiver type and a dot before the function name; the receiver is the class being extended.

Example

class

User

(

var name

:

String

)

// Add a printInfo function to the User class

fun User.

printInfo

(

)

{

    println

(

"Username $name"

)

}

fun main

(

)

{

    val user

=

User

(

"Runoob"

)

    user.

printInfo

(

)

 

// Call the extension function as if it were a member function

}

The output is:



用户名 Runoob

Inside an extension function body, this refers to the object before the dot at the call site, namely the receiver.

Example

// Add to MutableList an extension swap function

fun MutableList

<

Int

.

swap

(

index1

:

Int, index2

:

Int

)

{

    val tmp

=

this

[

index1

]

       

// this refers to the list on which swap is called

   

this

[

index1

]

=

this

[

index2

]

   

this

[

index2

]

=

tmp

}

fun main

(

)

{

    val list

=

mutableListOf

(

1

,

2

,

3

)

    list.

swap

(

0

,

2

)

             

// Swap the elements at indices 0 and 2

    println

(

list

)

}

The output is:



[3, 2, 1]

An extension function cannot access private members of the extended class because it never actually enters that class.


Extensions are resolved statically

Extension functions are not virtual members of the receiver type; which extension function is called is determined by the declared type of the object at the call site, not its runtime type.

Example

open

class

C

class

D

:

C

(

)

fun C.

foo

(

)

=

"c"

fun D.

foo

(

)

=

"d"

// Parameter c has declared type C, so it is bound to C.foo() at compile time

fun printFoo

(

c

:

C

)

{

    println

(

c.

foo

(

)

)

}

fun main

(

)

{

    printFoo

(

D

(

)

)

 

// Even when passed an instance of D, the output is still c

}

The output is:



c

In other words, extension functions are resolved only at compile time and take no part in polymorphic dispatch at runtime.

Member functions take priority

If an extension function has exactly the same signature as a class's own member function, the member function always wins at the call site.

Example

class

C

{

    fun foo

(

)

=

"Member function"

}

fun C.

foo

(

)

=

"Extension function"

fun main

(

)

{

    println

(

C

(

)

.

foo

(

)

)

 

// The member function wins

}

The output is:



成员函数

Note:An extension function can never override a member function. If you write an extension for a class and it later adds a method with the same name and parameters, your extension silently stops working. Keep this in mind when writing extensions for third-party libraries.

Nullable receiver

The receiver type can be nullable, so the extension function can be called even when the object is null.

Inside the function body, just check this == null; after the null check, the compiler smart-casts this to a non-null type.

Example

// The receiver is Any?, so even null can call this extension

fun

Any

?

.

describe

(

)

:

String

{

   

if

(

this

==

null

)

return

"Null value"

   

// After the null check, this is already a non-null type

   

return

"Non-null: $this"

}

fun main

(

)

{

    val text

:

String

?

=

null

    println

(

text.

describe

(

)

)

    println

(

"RUNOOB"

.

describe

(

)

)

}

The output is:



空值

非空:RUNOOB


Extension properties

Besides functions, Kotlin also allows extending a class with properties, written as the property name after the receiver type.

Because extensions do not actually insert fields into a class, an extension property has no backing field and cannot have an initializer; its behavior is entirely determined by the explicitly provided getter and setter.

Example

class

Site

(

val name

:

String

, val url

:

String

)

// Read-only extension property: only a getter is provided

val Site.

info

:

String

    get

(

)

=

"$name ($url)"

fun main

(

)

{

    val site

=

Site

(

"Runoob Tutorial"

,

"www.runoob.com"

)

    println

(

site.

info

)

}

The output is:



Runoob Tutorial (www.runoob.com)

An extension property can also be a var, as long as both a getter and a setter are provided.

Example

// var extension property: both getter and setter must be written explicitly

var StringBuilder.

lastChar

:

Char

    get

(

)

=

get

(

length

1

)

             

// Read the last character

    set

(

value

:

Char

)

{

        setCharAt

(

length

1

, value

)

   

// Modify the last character

   

}

fun main

(

)

{

    val sb

=

StringBuilder

(

"RUNOOB"

)

    println

(

sb.

lastChar

)

    sb.

lastChar

=

'!'

    println

(

sb

)

}

The output is:



B

RUNOO!

The following form is illegal because extension properties cannot have initializers.

Example

class

Foo

// Error: an extension property cannot have an initializer; it has no backing field

val Foo.

bar

=

1

// Correct form: provide an explicit getter

val Foo.

bar

:

Int

    get

(

)

=

1

Note:Extension properties must be top-level or belong to a class; they cannot be defined inside a function. Also, since there is no backing field, an extension property cannot cache computed results, and the getter logic runs again on every read.


Extensions to companion objects

If a class has a companion object, you can also add extension functions and properties to it.

Since companion object members can be accessed directly via the class name, these extensions behave like static members.

Example

class

MyClass

{

    companion object  

// This will be called Companion

}

// Add an extension function to the companion object

fun MyClass.

Companion

.

create

(

)

:

MyClass

=

MyClass

(

)

// Add an extension property to the companion object

val MyClass.

Companion

.

siteName

:

String

    get

(

)

=

"Runoob Tutorial"

fun main

(

)

{

    println

(

MyClass.

siteName

)

       

// Access the extension property via the class name

    println

(

MyClass.

create

(

)

is MyClass

)

}

The output is:



Runoob Tutorial

true

If the companion object has a name, just replace Companion with that name when extending it.


Extension scope and imports

Extensions are usually defined at the top level of a package. To use an extension defined in another package, you must import it just like a normal function.

Example

// File path: com/runoob/extensions/SiteExtensions.kt

package

com.runoob.extensions

class

Site

(

val name

:

String

, val url

:

String

)

// Top-level extension function belonging to package com.runoob.extensions

fun Site.

describe

(

)

:

String

=

"$name -> $url"

To use it from another package, you need to import the extension function's name.

Example

// File path: com/runoob/app/Main.kt

package

com.runoob.app

import

com.runoob.extensions.Site

import

com.runoob.extensions.describe

 

// Import the extension function

// You can also write import com.runoob.extensions.* to import the whole package

fun main

(

)

{

    val site

=

Site

(

"Runoob Tutorial"

,

"www.runoob.com"

)

    println

(

site.

describe

(

)

)

}

The output is:



Runoob Tutorial -> www.runoob.com

An extension is only visible in the scope where it is imported; the same extension name can be reused in different packages without conflict.


Member extensions: dispatch receiver and extension receiver

Extensions can also be declared inside a class, in which case they have two receivers.

The instance of the class defining the extension is the dispatch receiver, and the instance of the extended type is the extension receiver.

Example

class

D

{

    fun bar

(

)

=

"D.bar"

}

class

C

{

    fun baz

(

)

=

"C.baz"

   

// Define an extension function for D inside C

    fun D.

foo

(

)

:

String

{

        val fromExtension

=

bar

(

)

 

// A member of the extension receiver D

        val fromDispatch

=

baz

(

)

   

// A member of the dispatch receiver C

       

return

"$fromExtension / $fromDispatch"

   

}

    fun caller

(

d

:

D

)

=

d.

foo

(

)

}

fun main

(

)

{

    println

(

C

(

)

.

caller

(

D

(

)

)

)

}

The output is:



D.bar / C.baz

If both receivers have a member with the same name, the extension receiver takes priority; to access the dispatch receiver's member you must write this@ClassName.

Example

class

D

{

    fun bar

(

)

=

"D.bar"

}

class

C

{

    fun bar

(

)

=

"C.bar"

   

// Same name as D's bar

    fun D.

foo

(

)

:

String

{

        val first

=

bar

(

)

       

// The extension receiver wins, calling D.bar()

        val second

=

this

@C.

bar

(

)

// Explicitly specify the dispatch receiver, calling C.bar()

       

return

"$first / $second"

   

}

    fun caller

(

d

:

D

)

=

d.

foo

(

)

}

fun main

(

)

{

    println

(

C

(

)

.

caller

(

D

(

)

)

)

}

The output is:



D.bar / C.bar

An extension function defined as a member can be declared open and can be overridden in subclasses.

Dispatch is virtual for the dispatch receiver but remains static for the extension receiver.

Example

open

class

D

class

D1

:

D

(

)

open

class

C

{

    open fun D.

foo

(

)

=

"D.foo in C"

    open fun D1.

foo

(

)

=

"D1.foo in C"

    fun caller

(

d

:

D

)

=

d.

foo

(

)

 

// The parameter's declared type is D

}

class

C1

:

C

(

)

{

    override fun D.

foo

(

)

=

"D.foo in C1"

    override fun D1.

foo

(

)

=

"D1.foo in C1"

}

fun main

(

)

{

    println

(

C

(

)

.

caller

(

D

(

)

)

)

   

// The dispatch receiver is C

    println

(

C1

(

)

.

caller

(

D

(

)

)

)

 

// The dispatch receiver is C1, resolved virtually

    println

(

C

(

)

.

caller

(

D1

(

)

)

)

 

// The extension receiver is resolved statically by declared type D

}

The output is:



D.foo in C

D.foo in C1

D.foo in C


Common questions

The following covers the most error-prone areas when using extensions.

Problem Reason Solution
Calling an extension on a subclass object executes the superclass's extension Extensions are resolved statically by declared type Change the parameter type to the subclass, or switch to overriding a member function
Your own extension is "trumped" by the class's own same-named method Member functions always take priority over extension functions Rename the extension, or use a scope function to work around it
Writing an initializer for an extension property causes an error An extension property has no backing field Provide an explicit getter and setter instead
Wanting to access private members in an extension Extensions are not real members Access through the public API, or define the extension inside the same class
A written extension cannot be used in another file Extensions are not automatically visible across packages Use import to import the extension function or the whole package
Cannot tell the two this references apart in a member extension Both a dispatch receiver and an extension receiver exist Use this@OuterClassName to specify the dispatch receiver