Is there a neat trick to check two optionals to ensure that they aren't null before using them that I've missed? In Swift it is easy to do this, but embedding let blocks seems clunky.
Copy code
// 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)
}
}
b
brandonmcansh
12/07/2023, 4:32 PM
if (foo != null && bar != null) {
?
💯 1
t
Trey
12/07/2023, 4:33 PM
If they are declared as var, you have to assign them to val first so that they don't change.
👍 2
b
brandonmcansh
12/07/2023, 4:33 PM
Ah valid
p
Pablichjenkov
12/07/2023, 6:04 PM
"Early return" Might work sometimes:
Copy code
val foo = foo ?: return
val bar = bar ?: return
dosomething(foo, bar)
Assuming foo, bar are class properties.
Otherwise you would do
Copy code
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.
Copy code
val barCopy = bar ?: return Result.Error("bar unexpectedly null")
plus1 4
a
Anonymike
12/13/2023, 3:34 PM
I've been wanting to learn kotlin contracts to see if I can make some convenience methods for these kinds of things, but it is a bit tricky to make it pretty. Currently, we use the early return method a lot and sometimes with run in more complex scenario like http request validation:
Copy code
val couldBeNull = someProperty ?: run {
fail(400, "someProperty is required for this request")
return@request
}