Hello. We have discussion with our colleagues abou...
# codingconventions
d
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
Copy code
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
Copy code
fun createView(context : Context) : View {
  return with(context) {
    view = frameLayout {
    }
    view
  }
}
Copy code
fun createView(context : Context) : View {
  return with(context) {
    view = frameLayout {
    }.apply { view = this }
  }
}
Copy code
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
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
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
I don’t see big difference between apply and also in this case. Probably I would choosy apply
m
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
I would use
also
, see https://github.com/yole/kotlin-style-guide/issues/35 for my rationale
a
+1 for
also
.
apply
sounds like do some stuff on foo, while
also
sounds like do something else with foo
a
I have a question of my own regarding your code. Why don’t you write:
Copy code
fun createView(context : Context) : View {
  return with(context) {
    frameLayout {
    }.also { view = it }
  }
}
Why assign to
view
twice?
d
Hi, because i have an error in code, the first assignment shouldnt be there because it wont compile
a
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
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