How would I write an extension function for a `T?`...
# getting-started
c
How would I write an extension function for a
T?
. In Haskell, I use the maybe function pretty frequently. The type is like
(default: U, f: (T) -> U, x: T?): U
I would really like
nullableThing.maybe(default) { x -> … }
The closest I have got is
nullableThing?.let { x -> …} ?: default
which would be the body of the extension function. So, I guess I have two questions: how do I write the extension function and is this really the only way to implement this function?
Is there a stdlib function I am missing?
e
c
Yup! Exactly that. Nice
p
Shouldn't it be BAR?
Oh no right, when default the block doesn't apply
👍 1
c
Yeah, I think
?.letWithDefault
Would be a nice name.
As a Haskeller, I use this function A LOT
p
That's right, by the name I thought the lambda would apply always
.letAndApplyOrDefault()
perhaps
c
Yeah, I could see that just looking at the type signature. That is one possible implementation.
p
You see that a lot in Kotlin. firstOrNull, lastOrNull
c
I would just call it
maybe
but that is just how I am used to it being called.
p
I mean naming is hard
Got you
c
mapOr
isn’t bad
👍 1
m
The code provided for
letWith
is broken if
R
is nullable and
block
returns null.
👍 1
🔬 1
c
Oh, because it will always return the default. Good point. You probably want an explicit branch.