I'm finding myself getting frustrated with the fac...
# announcements
a
I'm finding myself getting frustrated with the fact that Kotlins optionals aren't actually
Optional
objects. Am I missing something here?
👌 1
Specifically, I'm interacting with RxJava right now and I need to be able to pass an "empty" object through an
Obseravble
. If Kotlins nullability represented actual
Optional
objects I'd be fine.
So now I'm in the position where I think I have to actually pull in an
Optional
library or build my own, and that seems super weird to do since nullability is built into the type system
j
That really has nothing to do with Kotlin. RxJava is the one whose implementation forbids
null
as a valid value.
a
That's a good point. Maybe my frustration has more to do with RxJava2 than Kotlin. I do like the fact that you don't get nested nulls in Kotlin
j
Kotlin's
Flow
type in the coroutine library allows nulls
a
Flow
is definitely on my list of things to learn. A bit out of scope for what I'm trying to do right now but I'm going to try and move in that direction anyways
c
I think I’d be sadder if Kotlin used optionals over just plain boring null. There are some cases where just catching the NPE and doing something else can be a cleaner and more elegant solution that the alternative. Poorly coded example below…
Copy code
class LocalUser(
    val apiKey: String?,
    val userId: Int?
)

class AuthenticationRecord(
    val apiKey: String,
    val userId: Int?
)

object NotAuthenticated

val authResponse = try {
    AuthenticationRecord(
        localUser.apiKey!!,
        localUser.userId!!
    )
} catch (ex: KotlinNullPointerException) {
    NotAuthenticated
}
j
Yeah that should definitely be rewritten to use normal null checking, but it also contains nothing that requires modeling optional types with null instead of an Optional box
c
😱 any reason to include the null checks over just expecting the null pointer exception?
j
It'll be ~100 times faster
😎 1
c
😅 that’s kind of what I was thinking, makes sense.
a
I don't follow the example and how it corresponds to optional objects vs just null checking.
c
Kotlin will force the exception to be thrown. Checking for null requires interacting with the properties twice, once for the null check and again for actually setting the value. So just expecting the exception reduces the lines of code required and declutters things. As Jake said though, it will be slower.