are there any advantages using Optional rather tha...
# announcements
e
are there any advantages using Optional rather than nullable type?
s
in Kotlin? not really, since you can do all the fun monadic stuff with
?.
and the scope functions
assuming you mean
java.util.Optional
, that is, the only real reason to use it is for java compatibility, afaict
but, there are some more strongly-enumerated Option/Maybe monads that folks have written for Kotlin, and they have their own benefits
1
e
like flatMap or something?
s
eh, flatMap isn’t really a thing you have to deal with nullables and safe navigation, the benefits I’m talking about are things like potentially more expressive APIs or different kinds of pattern matching
s
Like the ones from Arrow, where Optional is a monadic type as well, while
T?
isn’t .
s
https://arrow-kt.io/docs/0.10/apidocs/arrow-core-data/arrow.core/-option/index.html is a good read to get a handle on what a dedicated Option monad can provide
z
A pretty big advantage of
Optional
types is they let your type parameter be nullable itself. Otherwise you need to use a null sentinel, which can be awkward.
s
Some of the nullability is a bit weird. Eg this does not compile:
Copy code
class MyClass<T : Any?>() {
    val optionalValue: T? get() { TODO() }
    
    fun doSomething(callback: (T) -> Any) {
        callback(optionalValue)
    }
}
But this does (with an unchecked cast warning) and won’t throw null-pointer-exceptions:
Copy code
class MyClass<T : Any?>() {
    val optionalValue: T? get() { TODO() }

    fun doSomething(callback: (T) -> Any) {
        callback(optionalValue as T)
    }
}
I guess there are such things as
T??
types? 🙂
m
IIRC, Arrow is deprecating Option, and using null features instead.
e
@streetsofboston btw why do you cast T?? (which is T? actually) into T... I'd throw NoSuchElemException like java.
s
@E.Kisaragi My first code sample does not compile. The second example should not need a cast of
optionalValue as T
, since
T
has an upper bound of
Any?
(not
Any
) and
Any?
allows for
null
values... no need for throwing a NoSuchElementException, I just want to send
callback
a
null
when the value is
null
...
e
oh okay