This is more of Android specific. I need a referen...
# codereview
s
This is more of Android specific. I need a reference to dialog for further handling. "with" or "run"?
Copy code
dialog = with( AlertDialog.Builder( this ) ) {
        setTitle( "foo" )
        setMessage( "bar" )
        setCancelable(true)
        create()
    }.also {
        it.show()
    }

    or

    dialog = AlertDialog.Builder( this ).run {
        setTitle( "foo" )
        setMessage( "bar" )
        setCancelable(true)
        create()
    }.also {
        it.show()
    }
d
I like
with
slightly more but I don’t have a strong opinion
s
I started of using run but now prefer with
a
I usually like
apply
when I am initializing something and setting things up
Copy code
val dialog = AlertDialog.Builder(this).apply {
      setTitle( "foo" )
      setMessage( "bar" )
      setCancelable(true)
    }.show()
👍 3
s
Looks good, but apply returns the Builder and not the dialog itself and that rules out apply, also on builder
a
But
show()
gives you the dialog?
s
Nope, show returns void
I guess, you missed the create(). Create on builder returns the dialog
So it basically boils down to with, run or let
v
but with either of those you don’t need to do
also
at the end, you can just do
.show
directly
a
The
show()
I have used in my code is `AlertDialog.Builder`’s
show()
, since
apply
will return the
Builder
, which does return the
AlertDialog
s
isn't the last statement considered the return value? create() returns the dialog and show() is a member of the dialog and returns nothing (it just dispatches request to show the dialog)
Gotcha, i missed the show on the builder
with that, it looks more readable
a
you could do
Copy code
val dialog = AlertDialog.Builder(this).apply {
      setTitle( "foo" )
      setMessage( "bar" )
      setCancelable(true)
    }.create()
    .show()
h
why not just use method chaining? I dont think readability is being improved at all here
👍🏻 4
s
Suggestion from @apoorv9990 does it. It leverages a method on the builder which creates the object and requests a UI show as well
o
I don’t think you should spend time thinking of a solution because there is no problem here, just chain dotcalls as we always have
2
it’s only going to be something clever that the next person has to understand before they continue reading
a
This does not provide anything really, does it? It’s already a builder in itself