I find that a lot of times I have a nullable objec...
# announcements
e
I find that a lot of times I have a nullable object, and it sits in the middle of a call chain, and I don't want the whole chain to become nullable after it, and I don't want to use ?: because I have a sensible default that I could plug in. Could anything go wrong with using something like the following?
Copy code
fun <T: Any?> T?.or(other: T): T {
  return if(this == null) {
    other
  }
  else {
    this
  }
}
g
seems legit, i would clean it up a bit though:
Copy code
fun <T: Any?> T?.or(other: T) = this ?: other
👍 1
i would also consider naming it
orDefault(..)
because
or
implies some boolean logic
m
LGTM, but I think you don't need
?
in
<T : Any>
.
e
Thanks! @mg6maciej I always get confused as to the difference between
<T : Any>
and
<T : Any?>
m
If you specify
T
as
Any?
, you allow it to be null, so argument to your function can be null.
It also makes
?
in
T?.or
redundant.
If you specify the function as:
Copy code
fun <T: Any> T?.or(other: T) = this ?: other
it will not accept null as argument, but it will as receiver.
👍 1
e
@mg6maciej is there any way to only accept nullable receivers? What you have above allows me to call
or
on non-nullable objects.
s
why not just use
?:
?