Blog / May 10, 2021 / 2 mins read / By Suneet Agrawal

Why with function is not an Extension to Template class?

After reading my last blog about Kotlin with function, a lot of developers have asked me about, why with is not an extension to Template class like other scope functions?

Not only with, but run also has two implementations among which one is not an extension to Template class but a generic extension function.

The question is why?

with is an extension to generic class means it is not specific to any class. This could have been an extension to Any class which is the base class for all the classes, similar to java.lang.Object class in Java, even if you extend it or not. Or this could have been added as an extension to Template class which is compatible with Java objects also.

The reason it is not an extension to Any or Template class is that we don’t want to use it for chaining purpose. with will always be the starting point of any expression but it can’t be chained to any other object or expression.

For chaining purpose we have let, apply, also and other scope functions but not with.

Keep in mind that the result of with function can be chained further but the with function will never be used as chaining means it won’t be a second expression.

class Employee {
    var firstName: String = ""
    var age: Int = 0
}

val employee: Employee = Employee()

with(employee){
    firstName = "Suneet"
    age = 27

    println(firstName)
}

So to confirm that with can only be the starting point of any expression or it can’t be chained, with is not an extension to Any or Template class.

Comments