Skip to content

Instantly share code, notes, and snippets.

@JamesMenetrey
Created October 11, 2017 12:40
Show Gist options
  • Save JamesMenetrey/309e0405a37db37d25862e5096617555 to your computer and use it in GitHub Desktop.
Save JamesMenetrey/309e0405a37db37d25862e5096617555 to your computer and use it in GitHub Desktop.
Higher-kinded types in Scala
package scalaInAction.chapter8ScalableExtensibleComponents
import org.scalatest.{FlatSpec, Matchers}
trait HasAtLeastOneElement[F[_]] {
def any[A](xs: F[A]): Boolean
}
/**
* Higher-kinded types are types that know how to create a new type from the type argument. That's why
* higher-kinded types are also known as type constructors - they accept other types as a parameter and
* create a new type. <code>List(+A)</code> is an example of higher-kinded type.
*/
class HigherKindedTypes extends FlatSpec with Matchers {
"Higher-kinded types" can "abstract other types (kind of superset of types)" in {
val anOption = Some("One value")
val aNonEmptySeq = Seq(1, 2, 3)
val anEmptySeq = Seq()
val optionHandler = new HasAtLeastOneElement[Option] {
override def any[A](xs: Option[A]) = xs.isDefined
}
val seqHandler = new HasAtLeastOneElement[Seq] {
override def any[A](xs: Seq[A]) = xs.nonEmpty
}
optionHandler.any(anOption) should be (true)
seqHandler.any(aNonEmptySeq) should be (true)
seqHandler.any(anEmptySeq) should be (false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment