Open Close Principle and Extension Functions

I have learned that Open Close Principle is allowing extension to classes and restricting from modification. So in Kotlin, when we use extension function

  1. Are we extending a class
  2. Or are we modifying a class
  3. Can extension functions in kotlin be an example for Open/Close Principle?

I assume extension means to apply inheritance and modification means to add or change code of existing class.


2 answers

  • answered 2019-03-13 19:08 matwr

    The extenstion function is designed for situations where you want to add a function to a built-in or third-party class. You cannot do this by default because built-in functions are not modifiable.

    An example implementation to add a toUnsigned method to the built-in Byte class:

    fun Byte.toUnsigned(): Int {
        return if (this < 0) this + 256 else this.toInt()

    As Byte is a built-in class you cannot modify it directly. However, you can define an extension function as per above code. You can then call the extension function in the following way:

    val x: Byte = -1
    println(x.toUnsigned()) // Prints 255

    Keep in mind that this is just syntactic sugar - you're not actually modifying the class or its instances. Therefore, you have to import an extension function/property wherever you want to use it (since it isn't carried along with the instances of the class).

    Source :

  • answered 2019-03-14 14:48 ComDubh

    'Extension' in the context of the Open Closed Principle usually does not mean inheritance, it means somehow extending the class with new functionality. 'Modification' does refer to changing the code of the class, as you say.

    The extension facility of Kotlin allows you to add a method to a class without editing the code of the class. This is perfectly in keeping with the Open Closed Principle -- the class is extended with new functionality without the class itself being changed.