Hello. We have discussion with our colleagues about
also
vs
apply
usages. We have a method that needs to return some type but I would like to store instance of returned type to member property, something like
lateinit var view : View
fun createView(context : Context) : View {
return with(context) {
view = frameLayout {
}
}
}
this example would not compile because return type of view = frameLayout is unit. The variants to solve that are
fun createView(context : Context) : View {
return with(context) {
view = frameLayout {
}
view
}
}
fun createView(context : Context) : View {
return with(context) {
view = frameLayout {
}.apply { view = this }
}
}
fun createView(context : Context) : View {
return with(context) {
view = frameLayout {
}.also { view = it }
}
}
I prefer the
also
variant because it seems that this operator was made for this usages “do something also with this expression” and
apply
is for cases when i would like to modify instance in its context. Any opinions?