Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin

What are extension functions in Kotlin?

Educative Team

Overview

Kotlin allows us to “extend” classes without inheriting them by using extension functions. A function is said to be an extension function if it is added to the existing class.

We can define an extension function outside the class using the class name. We can then call it like other methods of the class.

Syntax

Let’s look at the syntax of the extension function given below:

fun classname.functionName()

A class can either be a primitive or a user-defined type.

Let’s have a look at an example in which we implement the extension function for a user-defined type.

class Circle (val radius: Double){
    fun area(): Double{
        return Math.PI * radius * radius;
    }
}
fun Circle.diameter(): Double{
    return 2*radius;
}
fun main(){
    val circle1 = Circle(5.0);
    println("Area of the circle is ${circle1.area()}")
    println("diameter of the circle is ${circle1.diameter()}")
}

Explanation

  • Lines 1–5: We define the Circle class with a property radius of the Double datatype. We also define a method area(), which will return the area of the circle.
  • Lines 6–8: We define an extension function diameter(), which will return the diameter of the circle.
  • Line 10: We create an object of the Circle class.
  • Line 11: We print the area of the circle by invoking the method area() of the Circle class.
  • Line 12: We print the diameter of the circle by invoking the extension function diameter() of the Circle class.

Let’s have a look at another example. In this example, we implement the extension function for a primitive type Int.

fun Int.square(): Int
{
  return this*this
}

fun main()
{
  val square: Int = 3.square()
  println("Squre of 3 is $square")
}

Explanation

  • Lines 1–4: We define an extension function square(), which will return the square of the given Int value.
  • Line 8: We invoke an extension function square() for the Int type.

RELATED TAGS

kotlin
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring