Inheritance vs Extension functions

This post was originally posted at and reposted on Medium on 3rd Dec 2019.


open class Person(var firstName : String,
protected var lastName : String) {
open fun getFullDetails() : String {
return "$firstName $lastName"
class Student : Person {
var rollNumber = 0

constructor(firstName : String,
lastName: String,
rollNumber : Int)
: super (firstName, lastName){
this.rollNumber = rollNumber

override fun getFullDetails() : String {
return "$firstName $lastName with Roll number as $rollNumber"
var student = Student ("Suneet", "Agrawal", 12)

Extension Function

class Employee(var firstName : String, var lastName : String) {
fun Employee.getFullDetails() : String {
return "$firstName $lastName"
var emp = Employee("Suneet", "Agrawal")

Merits of Extension functions

  • Can add functionality to a final class also. The class need not be a non-final (open) class.
  • Can add functionality without subclassing that means the object reference and the implementation can be of your base class.

Demerits of Extension functions

  • Can’t access the protected variables/properties or functions of your base class.
  • Can’t add any new variable/properties in your extension functions. You can add a property by just writing getter and setter but only without backing field. So basically you can’t add a field in the base class.

Merits of Inheritance

  • Can add new properties, override functions (non-final) of the base class.
  • Can access all protected variables and functions of the base class.

Demerits of Inheritance

  • Can’t extend a final class.




Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal

More from Medium

Kotlin Functions

Rx SwitchMap, Check before dispose

switch (Java) and when(Kotlin) are not fully interchangeable: here is why

Kotlin: Power of Extension functions