https://kotlinlang.org logo
Title
d

david.bilik

08/16/2017, 7:20 AM
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?
m

marstran

08/16/2017, 7:31 AM
I don't think you need to use
with
here. If
frameLayout
is a function on
Context
, you can try this:
return context.frameLayout {}.apply { k = this }
.
d

david.bilik

08/16/2017, 7:45 AM
Well thats not really a thing I wanted to discuss, this is just an really simple example, in real world the view is much more complicated and usage of
with
is justifiable.
g

gildor

08/16/2017, 7:56 AM
I don’t see big difference between apply and also in this case. Probably I would choosy apply
m

marstran

08/16/2017, 7:57 AM
The only difference between
apply
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.
k

kirillrakhman

08/16/2017, 9:35 AM
I would use
also
, see https://github.com/yole/kotlin-style-guide/issues/35 for my rationale
a

Andreas Sinz

08/16/2017, 10:46 AM
+1 for
also
.
apply
sounds like do some stuff on foo, while
also
sounds like do something else with foo
a

arekolek

08/22/2017, 1:41 PM
I have a question of my own regarding your code. Why don’t you write:
fun createView(context : Context) : View {
  return with(context) {
    frameLayout {
    }.also { view = it }
  }
}
Why assign to
view
twice?
d

david.bilik

08/22/2017, 1:43 PM
Hi, because i have an error in code, the first assignment shouldnt be there because it wont compile
a

arekolek

08/22/2017, 1:45 PM
I understand you can’t write
view = frameLayout {}
, but why assign twice? Why not assign only once in the
also
block like in the example I gave above?
d

david.bilik

08/22/2017, 1:46 PM
As I said, i have an error in the code snippet, i forgot to delete the first assignment when i copy/pasted it. It should`ve been exactly like your code .)
🆗 1