Blog / February 29, 2020 / 2 mins read / By Suneet Agrawal

Why let function is an Extension to Template class?

After reading my last blog about Kotlin let function, a lot of developers have asked me about, why let is an extension to Template class but not to Any class?

Not only let, but other helper functions like apply, also, takeIf and takeUnless are also extension functions to the Template class.

The question is why?

Any is the base class for all the classes, similar to java.lang.Object class in Java, even if you extend it or not. So if we want any of these functionalities in any class, Kotlin could have added these functions as an extension function to Any class but not to Template class.

Since we all know that Kotlin is an official language for Android which also supports Java.

To provide these functionalities for java objects also, which extends Object class, Kotlin has added these functions as an extension function to Template class.

If these were an extension to Any class, the object of classes written in Java was not been able to use these.

//Java code
public class Employee {
private String firstName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

@NonNull
@Override
public String toString() {
    return super.toString();
}
}

Now If Kotlin has added let function as an extension to Any class, the object of this Employee class couldn’t have used it.

But since the let function is an extension to Template class, this Employee class object can also use it.

//Kotlin code
val employee = Employee()
employee.let { 
    //do anything here
}

So to make these functions available for all the classes having any other superclass (like Object), Kotlin has added these functions as an extension to Template class.

Comments