https://kotlinlang.org logo
Title
t

Tomas Kormanak

11/12/2021, 12:13 PM
Is there some function like
with
which is ignoring return value and returns
Unit
? Something like this:
public inline fun <T> with(receiver: T, block: T.() -> Unit): Unit {
    receiver.block()
}
Or any better idea how to avoid explicitly returning Unit in this case:
fun process(data: Data) = with(data) {
    ///doSomething
    Unit
}
r

Rob Elliot

11/12/2021, 1:21 PM
You could always just use `apply`:
fun process(data: Data) {
  data.apply {
    // doSomething
  }
}
It’ll return
Data
rather than
Unit
but you can just discard that.
(It’s normally used for initialising a legacy object that relies on setters:
val person = Person().apply {
  name = ""
  dateOfBirth = TODO()
  ...
}
)
v

Vampire

11/12/2021, 1:36 PM
You could just specify the return type explicitly:
fun process(data: Data): Unit = with(data) {
    // ...
}
2
Or not using `=`e
fun process(data: Data) {
    with(data) {
        // ...
    }
}
j

Joffrey

11/12/2021, 1:40 PM
I usually find using a block body a bit clearer in general for functions that return
Unit
(instead of using an expression with
=
)
👍 1
r

Ruckus

11/12/2021, 3:44 PM
Might not be applicable depending on the broader context, but you could also just do
fun Data.process() {
   ///doSomething
}
1