diff --git a/core/src/main/scala/cats/data/NonEmptyList.scala b/core/src/main/scala/cats/data/NonEmptyList.scala index 15496a1115..875609c236 100644 --- a/core/src/main/scala/cats/data/NonEmptyList.scala +++ b/core/src/main/scala/cats/data/NonEmptyList.scala @@ -348,6 +348,12 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) { object NonEmptyList extends NonEmptyListInstances { def of[A](head: A, tail: A*): NonEmptyList[A] = NonEmptyList(head, tail.toList) + def ofInitLast[A](init: List[A], last: A): NonEmptyList[A] = + init match { + case Nil => NonEmptyList(last, Nil) + case h :: t => NonEmptyList(h, t :+ last) + } + def one[A](head: A): NonEmptyList[A] = NonEmptyList(head, Nil) /** diff --git a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala index dcfda5a120..55261d2aa5 100644 --- a/tests/src/test/scala/cats/tests/NonEmptyListTests.scala +++ b/tests/src/test/scala/cats/tests/NonEmptyListTests.scala @@ -74,6 +74,13 @@ class NonEmptyListTests extends CatsSuite { } } + test("Creating NonEmptyList with init/last + toList is identity") { + forAll { (init: List[Int], last: Int) => + val list = init :+ last + val nonEmptyList = NonEmptyList.ofInitLast(init, last) + list should === (nonEmptyList.toList) + } + } test("NonEmptyList#filter is consistent with List#filter") { forAll { (nel: NonEmptyList[Int], p: Int => Boolean) =>