is there a way of using `with` when the variable é...
# announcements
a
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
Copy code
private fun goToMain() = with(activity) {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finishAffinity()
}
v
You can replace it with
activity?.run { }
g
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
@ghedeon i guess
with
is more readable
g
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
An alternative is creating your own function, such as
withOptional
or something