Created
September 30, 2014 22:17
-
-
Save ceedubs/a96bc169eb3152cd6226 to your computer and use it in GitHub Desktop.
Scalaz's Equal type class (and associated handy === syntax) is a type-safe alternative to Scala's ==
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
scala> case class UserId(id: Long) | |
defined class UserId | |
scala> def isSusan(id: UserId): Boolean = id == 3L // see the bug? | |
isSusan: (id: UserId)Boolean | |
scala> isSusan(UserId(3L)) | |
res31: Boolean = false// shouldn't this be true? | |
// let's show the compiler how to check whether two UserIds are equal | |
scala> implicit val userIdEqual: Equal[UserId] = Equal.equalBy(_.id) | |
userIdEqual: scalaz.Equal[UserId] = scalaz.Order$$anon$7@33f02699 | |
scala> def isSusan2(id: UserId): Boolean = id === 3L // now the bug is a compile error | |
<console>:23: error: could not find implicit value for parameter F0: scalaz.Equal[Any] | |
def isSusan2(id: UserId): Boolean = id === 3L // now the bug is a compile error | |
^ | |
scala> def isSusan3(id: UserId): Boolean = id === UserId(3L) | |
isSusan3: (id: UserId)Boolean | |
scala> isSusan3(UserId(3L)) | |
res32: Boolean = true // ah there we go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment