https://kotlinlang.org logo
#announcements
Title
# announcements
m

mathew murphy

06/28/2019, 5:57 PM
Is there something that's like a combo of
use
and
with
?
s

Shawn

06/28/2019, 5:59 PM
What do you mean exactly by “combo”
m

mathew murphy

06/28/2019, 6:00 PM
e.g.
Copy code
db.getConnection().useWith {
  prepareStatement(...).useWith {
    setString(1, "Hello sailor")
    execute()
  }
}
s

Shawn

06/28/2019, 6:00 PM
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

bezrukov

06/28/2019, 6:05 PM
He also want connection to be closed after
run
or
apply
s

Shawn

06/28/2019, 6:06 PM
oh, whoops, forgot about use closing automatically
m

mathew murphy

06/28/2019, 6:12 PM
Sorry, this is JDBC, should have mentioned.
So yes, AutoClose is important.
m

Mike

06/28/2019, 6:14 PM
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

mathew murphy

06/28/2019, 6:14 PM
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

Mike

06/28/2019, 6:17 PM
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

mathew murphy

06/28/2019, 6:20 PM
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

gildor

06/29/2019, 6:42 AM
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
2 Views