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

Kotlin Interfaces

Kotlin Interfaces

An interface describes a set of capabilities or a contract; it tells callers "what this type can do" without restricting how it is implemented.

Kotlin's interfaces are more flexible than Java's: methods can have default implementations, and properties can have default getters.


Defining an interface

Define an interface with the interface keyword; it can contain abstract methods as well as default implementations with a body.

Interface members are public and open by default, the opposite of class members, which are final by default.

Example

// File path: Main.kt

interface

Site

{

   

// Abstract method: no body, implementers must override it

    fun name

(

)

:

String

   

// Method with a default implementation: implementers can use it directly or override it

    fun url

(

)

:

String

=

"www.runoob.com"

   

// A default implementation can call other members, including the abstract name()

    fun info

(

)

:

String

=

"Site: ${name()}, address: ${url()}"

}

// Override all

class

RunoobSite

:

Site

{

    override fun name

(

)

:

String

=

"RUNOOB"

    override fun url

(

)

:

String

=

"https://www.runoob.com"

}

// Override only the abstract method; url() and info() use the interface's default implementations

class

SimpleSite

:

Site

{

    override fun name

(

)

:

String

=

"Runoob"

}

fun main

(

)

{

    println

(

RunoobSite

(

)

.

info

(

)

)

    println

(

SimpleSite

(

)

.

info

(

)

)

}

Output result:



站点:RUNOOB,地址:https://www.runoob.com

站点:Runoob,地址:www.runoob.com

Default implementations let an interface add new methods in a backward-compatible way: old implementers keep compiling without overriding them.


Implementing an interface

When a class implements an interface, write the interface name after a colon; the class can also have a primary constructor, both written after the same colon.

All abstract members must be implemented, otherwise the class must be declared abstract.

Example

// File path: Main.kt

interface

Named

{

    fun label

(

)

:

String

}

// Implementation without a primary constructor

class

Simple

:

Named

{

    override fun label

(

)

:

String

=

"Simple"

}

// Implementation with a primary constructor: constructor parameters are written before the interface name

class

Site

(

val name

:

String

)

:

Named

{

    override fun label

(

)

:

String

=

"Site($name)"

}

fun main

(

)

{

   

// An interface can be the element type of a collection, holding different implementations

    val list

:

List

<

Named

=

listOf

(

Simple

(

)

, Site

(

"RUNOOB"

)

)

   

for

(

item in list

)

{

        println

(

item.

label

(

)

)

   

}

}

Output result:



Simple

Site(RUNOOB)

A class can implement multiple interfaces by separating them with commas, which compensates for the single-inheritance limit of classes.


Interface properties

An interface can declare properties, but it has no state, so properties cannot have backing fields or initializers.

Properties come in two forms: an abstract property declares only a type, while one with a getter has a default implementation.

Example

// File path: Main.kt

interface

Named

{

    val name

:

String

             

// Abstract property: implementers must provide it

   

// Property with a default getter: implementers can use it without overriding

    val displayName

:

String

        get

(

)

=

"[$name]"

   

// An interface can also declare var, but the setter is the implementer's responsibility

    var visits

:

Int

}

class

Site

(

override val name

:

String

)

:

Named

{

   

// The var property gets its storage and setter in the implementer

    override var visits

:

Int

=

0

}

fun main

(

)

{

    val site

=

Site

(

"RUNOOB"

)

    println

(

site.

displayName

)

    site.

visits

=

100

    println

(

"${site.name} visits: ${site.visits}"

)

}

Output result:



[RUNOOB]

RUNOOB 访问量:100

Important correction:Properties in an interface are not necessarily abstract. One can have a default getter like displayName this, which implementers inherit directly; only properties without a sensible default must be provided by the implementer.

But you cannot write val name: String = "RUNOOB" in an interface, because an interface holds no state and the compiler rejects the initializer.


Function overriding and super

When multiple interfaces provide default implementations of a member with the same name, the implementer must override that method, otherwise the compiler does not know which one to use.

When overriding, use super< to call each interface's implementation separately; this syntax also applies to properties.

Example

// File path: Main.kt

interface

A

{

    fun foo

(

)

:

String

=

"A.foo"

    val label

:

String

        get

(

)

=

"A.label"

}

interface

B

{

    fun foo

(

)

:

String

=

"B.foo"

    val label

:

String

        get

(

)

=

"B.label"

}

class

C

:

A, B

{

   

// Conflicting default implementations from two interfaces must be explicitly overridden

    override fun foo

(

)

:

String

=

super

<

A

.

foo

(

)

" | "

super

<

B

.

foo

(

)

    override val label

:

String

        get

(

)

=

super

<

A

.

label

" | "

super

<

B

.

label

}

fun main

(

)

{

    val c

=

C

(

)

    println

(

c.

foo

(

)

)

    println

(

c.

label

)

}

Output result:



A.foo | B.foo

A.label | B.label

If only one interface provides a default implementation and the other merely declares an abstract method, there is no conflict, and a normal override suffices.


Interface inheritance

An interface can inherit from one or more interfaces, declared with a colon; inherited abstract members are implemented by the final implementer.

If a subinterface overrides a default implementation, the implementer gets the subinterface's version first.

Example

// File path: Main.kt

interface

Base

{

    fun base

(

)

:

String

=

"Base"

}

interface

Left

:

Base

{

    fun left

(

)

:

String

=

"Left"

}

interface

Right

:

Base

{

   

// The subinterface overrides Base's default implementation

    override fun base

(

)

:

String

=

"Right overrode Base"

    fun right

(

)

:

String

=

"Right"

}

// Left and Right both inherit from Base; Impl only needs to handle it once

class

Impl

:

Left, Right

{

    override fun base

(

)

:

String

=

super

<

Right

.

base

(

)

}

fun main

(

)

{

    val impl

=

Impl

(

)

    println

(

impl.

base

(

)

)

    println

(

impl.

left

(

)

)

    println

(

impl.

right

(

)

)

}

Output result:



Right 重写了 Base

Left

Right

When interface inheritance forms a diamond, Kotlin requires the implementer to explicitly override the conflicting member, following the same rule as the previous section.


Interfaces vs. abstract classes

Both can declare abstract members and provide default implementations; the choice depends on whether state must be stored and whether multiple inheritance is needed.

Comparison Item an interface abstract classes
Can store state No; properties have no backing field Yes; properties can have backing fields
Can have constructors No Can have primary and secondary constructors
Multiple inheritance A class can implement multiple interfaces A class can extend only one abstract class
Default member visibility public, and open by default Regular members are final by default
Default implementation Supported; methods can have a body Supported; a regular method suffices
Typical use Define a capability contract and share behavior across types Reuse common implementation and express an is-a relationship

A rule of thumb: use an interface when you can express it as "can do something", and use an abstract class when you need to share state and common implementation.


Functional interfaces: fun interface

An interface with a single abstract method is a functional interface, declared with fun interface; since Kotlin 1.4 you can create an instance directly with a lambda.

This conversion is called SAM conversion, giving Kotlin interfaces the same writing convenience as Java functional interfaces.

Example

// File path: Main.kt

fun

interface

Validator

{

   

// The only abstract method

    fun validate

(

text

:

String

)

:

Boolean

   

// Non-abstract members do not affect whether it is a functional interface

    fun describe

(

)

:

String

=

"Validator"

}

fun check

(

text

:

String

, validator

:

Validator

)

:

String

=

   

if

(

validator.

validate

(

text

)

)

"\"$text\" passed validation"

else

"\"$text\" failed validation"

fun main

(

)

{

   

// Build an instance of the fun interface directly with a lambda

    val notEmpty

=

Validator

{

it.

isNotEmpty

(

)

}

    println

(

check

(

"RUNOOB"

, notEmpty

)

)

    println

(

check

(

""

, notEmpty

)

)

    val shorter

=

Validator

{

it.

length

<=

10

}

    println

(

check

(

"www.runoob.com"

, shorter

)

)

    println

(

shorter.

describe

(

)

)

}

Output result:



「RUNOOB」通过校验

「」未通过校验

「www.runoob.com」未通过校验

校验器

Even an ordinary interface with only one abstract method cannot be written this way; it must have the fun modifier.

Note:The single abstract method of a fun interface cannot be a suspend function; this is a compiler restriction.


Common questions

The following are the most frequently asked questions about using interfaces.

Why can't properties in an interface have initializers

An interface has no state and properties cannot have backing fields, so val x: Int = 1 reports an error; write a getter if you need a default value.

Are interface methods final by default

No. Interface members are open by default, and both subinterfaces and implementers can override them.

Can a class implement multiple interfaces

Yes. Classes can only single-inherit, but you can list multiple interfaces separated by commas; conflicting default implementations must use super< to disambiguate.

Can an interface have a constructor

No. An interface holds no state and naturally needs no constructor; if you need a constructor, use an abstract class.

Can a regular interface be instantiated with a lambda

No; only a fun interface works. This feature has been available since Kotlin 1.4.