Trey
12/07/2023, 4:29 PM// Kotlin
fun doSomething(foo: String, bar: String) {
// ...
}
fun test() {
var foo: String? = null
var bar: String? = "foo"
foo?.let { f ->
bar?.let { b ->
// use foo and bar
doSomething(foo, bar)
}
}
}
vs
// Swift
func test() {
var foo: String? = null
var bar: String? = "foo"
if let foo = foo, let bar = bar {
doSomething(foo: foo, bar: bar)
}
}
brandonmcansh
12/07/2023, 4:32 PMTrey
12/07/2023, 4:33 PMbrandonmcansh
12/07/2023, 4:33 PMPablichjenkov
12/07/2023, 6:04 PMval foo = foo ?: return
val bar = bar ?: return
dosomething(foo, bar)
Assuming foo, bar are class properties.
Otherwise you would do
val barCopy = bar ?: return
I like this pattern when the function returns a resultsuccess, error that way you return an error whenever a null fails, providing fine detail to the consumer.
val barCopy = bar ?: return Result.Error("bar unexpectedly null")
Anonymike
12/13/2023, 3:34 PMval couldBeNull = someProperty ?: run {
fail(400, "someProperty is required for this request")
return@request
}