About "with" statement


Hi. As You know, the “with” statement, that can help us to write less code, has the “dark side”: sometimes we can’t understand, whose method or property are used. And if we use cascade of “with”, it is much worse. Somebody say: “Don’t use with!”, but we want to write less code!!!

This problem was solved long ago in SQL (“from” aliases), but not in programming languages. Why?!!
Why I can’t write something about below?
with myVeryLongAndBeautifullVar a, myOtherGreatThing.megaFunction(a) b { return if (b != a) then b else a; }
with somebody s { with People() f { f.children.add(s); s.parents.add(f); } }

That’s too far-fetched examples, but I think, the principle is understood.
May be, I will see something alike in the Kotlin at future times?


You can use let function exactly for that:

somebody.let { s ->
    People().let { f -> 


Yes, I can. But it’s not a perfect code, IMHO. Because here I emulate traditional language construction with some other. Someone will see this and think: "Ah! I see very long lamda! What did he mean by that? May be He don’t understand, lamda must be short for readable"
Other will read the documentation about .let and will not find any with-like template. But that code: with (foofoofoo f, barbarbar b) {f.a = b.a; f.bb(); b.f(f.f)} is more readable and understandable for anyone from any language.

If “Someone not-from-Kotlin” (it is me, for example) will want to use “with”, he or she will read the documentation at a chapter “with”, I think. He or she can read: “In the Language You can have more control under with!!! Enjoy!”, or “we are like all, sorry.”

Good feature for future, I think.


There is absolutely no rule in Kotlin saying that lambdas must be short. In fact, the opposite is true: lambdas in Kotlin intentionally look like regular statements in other languages like Java, and they can be as long as those statements.

Also, following your logic, every standard library function should become a language feature to make it more discoverable. This used to work well for languages like BASIC, but it doesn’t scale to modern languages.


Ok, I agree. Kotlin inplements a new paradigm, and I know one piece of it now. Can You recommend official (or thereabouts) source for other pieces? Best prctices, new solutions for traditional problems? Perhaps I need to rethink my old-school experience. Thanks.


We try to collect such information on the Idioms page: http://kotlinlang.org/docs/reference/idioms.html


You could write your own with function that comes close:

fun <A, B, C> with(a: A, b: B, f: (A, B) -> C) = f(a, b)

And then you could use it like this:

val myLongName = 1
val myOtherLongName = 2

with(myLongName, myOtherLongName) { my1, my2 -> 
   my1 + my2
// = 3

Using 'with(...)' Function with Multiple Receivers?

Excellent! Thank you, Medium. I really need to rethink all my experience :slight_smile:. So I went to change the mindset.