Why let function is an Extension to Template class?

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

This post was originally posted at https://agrawalsuneet.github.io/blogs/why-let-function-is-an-extension-to-template-class/ and reposted on Medium on 26th Feb 2020.

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 class, 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.

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

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