1

I was wondering if there's a standard function which behaves similarly to let but returns the receiver itself, not the value calculated by block.

My piece of code with let:

fun rightParts(s: Lexeme) = 
    rightPartsByLeft[s] ?:
    ArrayList<Rule>() let { rightPartsByLeft[s] = it; it }
                                                      ^ here's the statement which I would
                                                        like to avoid

So, if there would be such a function named, for example, btw, the code above would shorten a little and become more expressive:

 fun rightParts(s: Lexeme) = 
     rightPartsByLeft[s] ?:
     ArrayList<Rule>() btw { rightPartsByLeft[s] = it }

Of course, I might write this function by myself and include it into every project, but I suppose, people would like a function with such semantics.

Or is there another nice way of doing the same in Kotlin?

hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 1
    There's no such function AFAIK, but in your example, if I'm guessing correctly that `rightPartsByLeft` is a `MutableMap`, then you can do `rightPartsByLeft.getOrPut(s) { ArrayList() }` – Alexander Udalov Jun 14 '15 at 14:47
  • @AlexanderUdalov, thanks, it is not universal solution, but it seems perfect for this particular case. – hotkey Jun 14 '15 at 16:40
  • Kotlin now has [`apply()` extension function](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html) which you can use on anything. – Jayson Minard Jan 05 '16 at 22:10

0 Answers0