Skip to content

Commit

Permalink
Inline NonEmpty maps (#3120)
Browse files Browse the repository at this point in the history
  • Loading branch information
serras authored Aug 30, 2023
1 parent 02215d4 commit a7dc178
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,18 @@ public class NonEmptyList<out A>(
public override inline fun <B> map(transform: (A) -> B): NonEmptyList<B> =
NonEmptyList(transform(head), tail.map(transform))

override fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> mapIndexed(transform: (index: Int, A) -> B): NonEmptyList<B> =
NonEmptyList(transform(0, head), tail.mapIndexed { ix, e -> transform(ix + 1, e) })

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
transform(head).toNonEmptyList() + tail.flatMap(transform)

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <K> distinctBy(selector: (A) -> K): NonEmptyList<A> =
all.distinctBy(selector).toNonEmptyListOrNull()!!

public operator fun plus(l: NonEmptyList<@UnsafeVariance A>): NonEmptyList<A> =
this + l.all

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import kotlin.jvm.JvmInline

@JvmInline
public value class NonEmptySet<out A> private constructor(
private val elements: Set<A>
@PublishedApi internal val elements: Set<A>
) : Set<A> by elements, NonEmptyCollection<A> {

public constructor(first: A, rest: Set<A>) : this(setOf(first) + rest)
Expand All @@ -21,6 +21,25 @@ public value class NonEmptySet<out A> private constructor(

override fun lastOrNull(): A = elements.last()

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> map(transform: (A) -> B): NonEmptyList<B> =
elements.map(transform).toNonEmptyListOrNull()!!

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> mapIndexed(transform: (index: Int, A) -> B): NonEmptyList<B> =
elements.mapIndexed(transform).toNonEmptyListOrNull()!!

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
elements.flatMap(transform).toNonEmptyListOrNull()!!

override fun distinct(): NonEmptyList<A> =
toNonEmptyList()

@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <K> distinctBy(selector: (A) -> K): NonEmptyList<A> =
elements.distinctBy(selector).toNonEmptyListOrNull()!!

override fun toString(): String = "NonEmptySet(${this.joinToString()})"

@Suppress("RESERVED_MEMBER_INSIDE_VALUE_CLASS")
Expand Down

0 comments on commit a7dc178

Please sign in to comment.