Why let function is an Extension to Template 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.

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.

//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();
}
}
//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.

--

--

https://agrawalsuneet.github.io/

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