Skip to content

Mono.mapNotNull should produce a non-nullable type in Kotlin #52

Open
@MartinHeyer

Description

@MartinHeyer

Motivation

Please consider the following example, where a Mono shall produce a lookup result or nothing if map.get() returns null.

    Mono.just(mapOf("foo" to "bar")).mapNotNull { it["foo"] } 
    // produces Mono<String?> but should be Mono<String> instead

The Kotlin compiler could know that the inner type must be non-null.

Project Reactor's code does not seem to signal any @NonNull.
Reactor-kotlin-extensions does not seem to extend the mapNonNull() operator.

Desired solution

The mapNotNull operator should produce a Mono<X> instead of Mono<X?>.
Reactor-kotlin-extensions could override Mono / Flux mapNotNull() to hint the correct type to the kotlin compiler.

Considered alternatives

Currently I just Mono.cast<> the result to non-null, which is suboptimal and requires knowledge of the correct class.
With Kotlin 1.7's new definitely not null types, one could just do:

    fun <R, T>Mono<T>.mapNotNullTyped(mapper: (T) -> R) : Mono<R & Any> {
        return this.mapNotNull(mapper) as Mono<R & Any> //rely on mapNotNull not to produce null, else throw
    }

Update: This simple implementation works on my machine:

    private fun <R, T> Mono<T>.mapNotNullTyped2(mapper: (T) -> R?): Mono<R> {
        return this.mapNotNull(mapper)
    }

Additional context

Tested with

  • reactor-core:3.4.21
  • reactor-kotlin-extensions:1.1.7

Thank you very much

Martin

Metadata

Metadata

Assignees

No one assigned

    Labels

    ❓need-triageThis issue needs triage, hasn't been looked at by a team member yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions