Is there something that's like a combo of `use` an...
# announcements
m
Is there something that's like a combo of
use
and
with
?
s
What do you mean exactly by “combo”
m
e.g.
Copy code
db.getConnection().useWith {
  prepareStatement(...).useWith {
    setString(1, "Hello sailor")
    execute()
  }
}
s
T.run {}
has a signature of
(T.() -> R) -> R
, maybe that’s what you want?
I’m assuming
prepareStatement
is a method on the connection from
getConnection
?
you might just want
apply {}
if you’re just returning
Unit
b
He also want connection to be closed after
run
or
apply
s
oh, whoops, forgot about use closing automatically
m
Sorry, this is JDBC, should have mentioned.
So yes, AutoClose is important.
m
Is it really that much more to stick with
use
and
it
? Or give the parameter a meaningful name to eliminate ambiguity in usage? Sometimes less concision leads to higher readability.
m
Sure, I've gone ahead and used
use
. I was just wondering if there was an even shorter way to do it.
If anything I feel like Kotlin offers too many convenient shortcuts to eliminating code, but I'm coming to it from Go... (and Java)
m
I'd agree that sometimes there are too many ways to do something. There are docs that provide some conventions, mostly around let/apply/also/run/with that seem to be consistent, but definitely other areas where it's vague.
m
Docs in general are a bit skimpy, getting OkHttp and Moshi working was frustrating, partly because even when libraries are written in Kotlin it often seems to be the case that they're documented on the assumption that you're calling them from Java.
Also, how coroutines relate to threads and suspend functions relate to blocking calls could use some careful explanation.
But, I'm doing the same work with massively less code in the end, and that's a good thing.
g
Do you have any example why do you need this? Why not just: e.g.
Copy code
db.getConnection().use { connection ->
  connection.prepareStatement(...).use { statement ->
    statement.setString(1, "Hello sailor")
    statement.execute()
  }
}
I mean multiple nested context are not something pleasant to use imp
But it's easy to implement this useWith extension