Build Status Maven Central

Newts defines newtypes compatible with cats typeclasses.

libraryDependencies ++= Seq(
  "com.github.julien-truffaut" %%  "newts-core"  % "0.1.1"
)

Example

Using cats you can squash values using Monoid or Semigroup instance (based on if your data structure can be empty):

import cats.data.NonEmptyList
import cats.instances.all._
import cats.syntax.all._

val ints    = 1.to(100).toList
val intNel  = NonEmptyList(1, 2.to(100).toList)
val strings = List("abc", "cde", "fgh")
scala> ints.combineAll
res1: Int = 5050

scala> intNel.reduce
res2: Int = 5050

scala> strings.combineAll
res3: String = abccdefgh

However, some types have more than one valid instance of a typeclass, e.g. (+, 0) and (*, 1) are two completely valid Monoid. A solution to this problem is to chose one instance somehow arbitrarily and create a wrapper type for each other implementation. This pattern is called newtype and it comes from the haskell language.

import cats.Monoid

implicit val longMonoid: Monoid[Long] = new Monoid[Long] {
  def empty: Long = 0
  def combine(x: Long, y: Long): Long = x + y
}

case class Mult(value: Long)

implicit val longMult: Monoid[Mult] = new Monoid[Mult] {
  def empty: Mult = Mult(1)
  def combine(x: Mult, y: Mult): Mult = Mult(x.value * y.value)
}

Here are a few examples of newtypes define in newts:

import newts._
scala> ints.foldMap(i => LastOption(Some(i)))
res7: newts.LastOption[Int] = LastOption(Some(100))

scala> intNel.reduceMap(First(_))
res8: newts.First[Int] = First(1)

scala> intNel.reduceMap(Min(_))
res9: newts.Min[Int] = Min(1)

scala> intNel.reduceMap(Max(_))
res10: newts.Max[Int] = Max(100)

scala> strings.foldMap(Dual(_))
res11: newts.Dual[String] = Dual(fghcdeabc)

Instead of using newtype constructors, one can use newts.syntax:

import newts.syntax.all._
import cats.syntax.all._
scala> strings.foldMap(_.asDual)
res12: newts.Dual[String] = Dual(fghcdeabc)

scala> ints.foldMap(_.some.asLastOption)
res13: newts.LastOption[Int] = LastOption(Some(100))

Maintainers and contributors

The current maintainers (people who can merge pull requests) are:

and the contributors (people who committed to newts).

Newts is licensed under the [Apache License, Version 2.0][http://www.apache.org/licenses/LICENSE-2.0] (the “License”); you may not use this software except in compliance with the License.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.