All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.arrow.core.NonEmptyCollection.kt Maven / Gradle / Ivy

There is a newer version: 2.0.1
Show newest version
package arrow.core

/**
 * Common interface for collections that always have
 * at least one element (available from [head]).
 */
public interface NonEmptyCollection : Collection {
  override fun isEmpty(): Boolean = false
  public val head: E

  public operator fun plus(element: @UnsafeVariance E): NonEmptyCollection
  public operator fun plus(elements: Iterable<@UnsafeVariance E>): NonEmptyCollection

  public fun toNonEmptySet(): NonEmptySet = toNonEmptySetOrNull()!!
  public fun toNonEmptyList(): NonEmptyList = toNonEmptyListOrNull()!!

  // These functions take precedence over the extensions in [Collection].
  // This way non-emptiness is tracked by the type system.

  public fun firstOrNull(): E = head
  public fun lastOrNull(): E

  public fun distinct(): NonEmptyList =
    delegate { it.distinct() }
  public fun  distinctBy(selector: (E) -> K): NonEmptyList =
    delegate { it.distinctBy(selector) }
  public fun  flatMap(transform: (E) -> NonEmptyCollection): NonEmptyList =
    delegate { it.flatMap(transform) }
  public fun  map(transform: (E) -> T): NonEmptyList =
    delegate { it.map(transform) }
  public fun  mapIndexed(transform: (index:Int, E) -> T): NonEmptyList =
    delegate { it.mapIndexed(transform) }
  public fun  zip(other: NonEmptyCollection): NonEmptyCollection> =
    delegate { it.zip(other) }

  /**
   * Convenience method which delegates the implementation to [Collection],
   * and wraps the resulting [List] as a non-empty one.
   */
  private inline fun  delegate(crossinline f: (Collection) -> List): NonEmptyList =
    f(this as Collection).toNonEmptyListOrNull()!!
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy