https://kotlinlang.org logo
Title
a

amadeu01

03/18/2019, 12:58 PM
is there a way of using
with
when the variable é optional? for instance, inside a fragment, the
activity
is optional, so can I use something like
private fun goToMain() = with(activity) {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finishAffinity()
}
v

Vladimir Petrakovich

03/18/2019, 1:00 PM
You can replace it with
activity?.run { }
g

ghedeon

03/18/2019, 1:04 PM
Right, it was discussed before, basically
.run{}
is the equivalent of
with
plus nullable support, so one might think that the usage of
with
is a bit questionable.
a

amadeu01

03/18/2019, 1:08 PM
@ghedeon i guess
with
is more readable
g

ghedeon

03/18/2019, 1:16 PM
I'm inclined to agree with you. I went through the same process: was using
with
then realised this limitation, then didn't want to mix both for basically the same thing and refactor every time I switch null/nullable... Ended up using
.run
almost everywhere.
l

LeoColman

03/18/2019, 1:34 PM
An alternative is creating your own function, such as
withOptional
or something