david.bilik
08/16/2017, 7:20 AMalso 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?marstran
08/16/2017, 7:31 AMwith here. If frameLayout is a function on Context, you can try this: return context.frameLayout {}.apply { k = this }.david.bilik
08/16/2017, 7:45 AMwith is justifiable.gildor
08/16/2017, 7:56 AMmarstran
08/16/2017, 7:57 AMapply and also is that apply takes an extension function (so that the parameter is given as this), while also takes a normal function. The also function was added to Kotlin 1.1 to deal with the case where apply would shadow this from the outer scope.kirillrakhman
08/16/2017, 9:35 AMalso, see https://github.com/yole/kotlin-style-guide/issues/35 for my rationaleAndreas Sinz
08/16/2017, 10:46 AMalso. apply sounds like do some stuff on foo, while also sounds like do something else with fooarekolek
08/22/2017, 1:41 PMfun createView(context : Context) : View {
return with(context) {
frameLayout {
}.also { view = it }
}
}
Why assign to view twice?david.bilik
08/22/2017, 1:43 PMarekolek
08/22/2017, 1:45 PMview = frameLayout {}, but why assign twice? Why not assign only once in the also block like in the example I gave above?david.bilik
08/22/2017, 1:46 PM