Skip to content

Add a Map utility to this package #17

@blackbird-simon

Description

@blackbird-simon

When we've been using this library there are often times where it can be useful to apply a function to the interior value of a nullable field before further processing.

While it's a simple utility to write, it feels like it would be an ergonomic to have such a utility exposed as part of this package. Something like

func Map[T1, T2 any](maybeValue Nullable[T1], fn func(value T1) T2) Nullable[T2] {
	if !maybeValue.IsSpecified() {
		return nil
	} else if maybeValue.IsNull() {
		return NewNullNullable[T2]()
	} else {
		// SAFETY: Must is safe to use here as all other states of the nullable.Nullable value
		// are checked in the above if blocks.
		return NewNullableWithValue(fn(maybeValue.MustGet()))
	}
}

With a usage like

result := nullable.Map(maybeValue, func(x int) int { return x + 1 })

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions