https://kotlinlang.org logo
#announcements
Title
# announcements
e

eygraber

03/16/2017, 4:50 PM
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

gjesse

03/16/2017, 4:52 PM
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

mg6maciej

03/16/2017, 4:54 PM
LGTM, but I think you don't need
?
in
<T : Any>
.
e

eygraber

03/16/2017, 4:58 PM
Thanks! @mg6maciej I always get confused as to the difference between
<T : Any>
and
<T : Any?>
m

mg6maciej

03/16/2017, 5:06 PM
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

eygraber

03/16/2017, 8:42 PM
@mg6maciej is there any way to only accept nullable receivers? What you have above allows me to call
or
on non-nullable objects.
s

stepango

03/23/2017, 10:42 AM
why not just use
?:
?
5 Views