Skip to content

Commit

Permalink
implement NonEmptyChunk.unapplySeq (zio#4310)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgfraser authored Oct 12, 2020
1 parent 64bea7f commit 27b960f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
31 changes: 30 additions & 1 deletion core-tests/shared/src/test/scala/zio/NonEmptyChunkSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,35 @@ object NonEmptyChunkSpec extends ZIOBaseSpec {
val expected = as.init.foldRight(map(as.last))(reduce)
assert(actual)(equalTo(expected))
}
}
},
suite("unapplySeq")(
zio.test.test("matches a nonempty chunk") {
val chunk = Chunk(1, 2, 3)
val actual = chunk match {
case NonEmptyChunk(x, y, z) => Some((x, y, z))
case _ => None
}
val expected = Some((1, 2, 3))
assert(actual)(equalTo(expected))
},
zio.test.test("does not match an empty chunk") {
val chunk = Chunk.empty
val actual = chunk match {
case NonEmptyChunk(x, y, z) => Some((x, y, z))
case _ => None
}
val expected = None
assert(actual)(equalTo(expected))
},
zio.test.test("does not match another collection type") {
val vector = Vector(1, 2, 3)
val actual = vector match {
case NonEmptyChunk(x, y, z) => Some((x, y, z))
case _ => None
}
val expected = None
assert(actual)(equalTo(expected))
}
)
)
}
9 changes: 9 additions & 0 deletions core/shared/src/main/scala/zio/NonEmptyChunk.scala
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,15 @@ object NonEmptyChunk {
def single[A](a: A): NonEmptyChunk[A] =
NonEmptyChunk(a)

/**
* Extracts the elements from a `NonEmptyChunk`.
*/
def unapplySeq[A](seq: Seq[A]): Option[Seq[A]] =
seq match {
case chunk: Chunk[A] if chunk.nonEmpty => Some(chunk)
case _ => None
}

/**
* The unit non-empty chunk.
*/
Expand Down

0 comments on commit 27b960f

Please sign in to comment.