Created
October 11, 2017 12:40
-
-
Save JamesMenetrey/309e0405a37db37d25862e5096617555 to your computer and use it in GitHub Desktop.
Higher-kinded types in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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