Gyuhyeon
02/10/2020, 5:24 AM/* Case A: java-style */
val result = repository.select()
if (result != null) {
doSomething() // business logic
} else {
doSomethingElse() // business logic
}
/* Case B: Kotlin style...? */
repository.select()?.also {
doSomething()
} ?: run {
doSomethingElse()
}
/* Case C: Kotlin style... + better job security through code only the creater can understand? */
try {
repository.select()!!.run {
doSomething()
}
} catch (NullPointerException e) { // or whatever it was that catches not null assertion error
doSomethingElse()
}
What is the better solution here? Obviously we can't make repository.select return non nullable type because that will result in an exception anyway. Business logic requires a different action for nonexisting row, and the only way to do this is either catch an exception, use obscure code with .also
and ?:
, or use plain old java style code. Is there any other solution to this?nils
02/10/2020, 5:29 AM?.let
instead of ?.also
in your second exampleGyuhyeon
02/10/2020, 5:31 AM?.also
would be a better way since if we do ?.let
and then the last line inside the block returns null for whatever reason, the ?: run
block would be triggered. ?.also
guarantees that ?: run
will only be triggered when the select
itself is null.Fleshgrinder
02/10/2020, 6:07 AMstreetsofboston
02/10/2020, 1:51 PMpt
02/10/2020, 6:16 PMfun doSomething(data: Data) = ...
// doesn't compile
val result: Data? = repository.select()
doSomething(result)
// compiles
val result: Data? = repository.select()
if (result != null) {
doSomething(result)
} else {
doSomethingElse()
}
Steve
02/10/2020, 6:39 PMstreetsofboston
02/10/2020, 8:19 PMFleshgrinder
02/11/2020, 5:51 AM