Logo
Kotlin Basics
Kotlin BasicsInterfaces and Extensions

Interfaces and Extensions

Introduction to interfaces for defining blueprints and extensions for adding functionalities in Kotlin. This section covers the syntax, usage, and best practices for working with interfaces and extensions.

In Kotlin, interfaces and extensions are powerful features that allow you to define blueprints for classes and extend the functionality of existing classes, respectively. This section will guide you through the basics of using interfaces and extensions in Kotlin.

Interfaces

Syntax

The basic syntax for defining an interface in Kotlin is as follows:

interface InterfaceName {
    fun method1()
    fun method2()
    // ...
}

Example

Here's a simple interface that defines a blueprint for a shape.

interface Shape {
    fun draw()
    fun area(): Double
}

Implementing Interfaces

Classes can implement interfaces using the : (colon) syntax.

class Circle(val radius: Double) : Shape {
    override fun draw() {
        println("Drawing a circle.")
    }
 
    override fun area(): Double {
        return Math.PI * radius * radius
    }
}

Extensions

Syntax

The basic syntax for defining an extension function in Kotlin is as follows:

fun ClassName.methodName() {
    // Extension code
}

Example

Here's a simple extension function that adds a printUpperCase() method to the String class.

fun String.printUpperCase() {
    println(this.toUpperCase())
}

Usage

You can use the extension function as if it were a regular method on the class.

"hello".printUpperCase()  // Output: HELLO

When to Use Each

  • Interfaces: Use interfaces to define a common blueprint that multiple classes can adhere to. They are especially useful for defining contracts in your code.

  • Extensions: Use extensions to add new functionalities to existing classes without modifying them. This is particularly useful for classes that you don't own or can't modify.

Summary and Best Practices

  • Use interfaces to define blueprints for classes.
  • Use extensions to add functionalities to existing classes.
  • Always specify the types and visibility modifiers explicitly for better readability.

Interfaces and extensions are invaluable tools in Kotlin for defining contracts and extending functionalities, respectively. Whether you're working on Android Native development or general Kotlin projects, understanding how to use these features effectively can significantly improve your code quality and productivity.

Book a conversation with us for personalize training today!

Was this helpful?
Logo