Last active
November 24, 2017 19:06
-
-
Save d6y/511d762f3b60ede067db67bc5f03a791 to your computer and use it in GitHub Desktop.
Equality
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
/* | |
By default, there are equality tests in Scala that return false which you'd really like | |
to be a compile-time error. | |
For example: | |
scala> "Hello" == 42 | |
res0: Boolean = false | |
scala> Some(1) == 1 | |
<console>:12: warning: comparing values of types Some[Int] and Int using `==' will always yield false | |
Some(1) == 1 | |
Here are three ways to fix this to varying degrees... | |
See also: | |
- future language warning changes: http://dotty.epfl.ch/docs/reference/multiversal-equality.html | |
*/ | |
object Scala { | |
// Use "-Xfatal-warnings" | |
// Option[Int] and Int are unrelated: they will most likely never compare equal | |
def test1: Boolean = Option(1) == 1 | |
// Silent (no error or warning) | |
// Presumably toString is happening, which I thought could be disabled with WartRemover | |
// but apparently not yet: https://github.com/wartremover/wartremover/issues/403 | |
def test2: Boolean = "Hello" == 42 | |
// comparing values of types Int and String using `==' will always yield false | |
def test3: Boolean = 42 == "Hello" | |
} | |
object SE { | |
import org.scalactic.TypeCheckedTripleEquals._ | |
// types Some[Int] and Int do not adhere to the type constraint selected for the === and !== operators; | |
// the missing implicit parameter is of type org.scalactic.CanEqual[Some[Int],Int] | |
def test1: Boolean = Option(1) === 1 | |
def test2: Boolean = "Hello" === 42 | |
} | |
object Cats { | |
import cats.implicits._ | |
// type mismatch; | |
// found : Int(1) | |
// required: Option[Int] | |
def test1: Boolean = Option(1) === 1 | |
def test2: Boolean = "Hello" === 42 | |
} | |
/* | |
NB: | |
settings(wartremoverErrors in Compile += Wart.Equals) | |
...disables `==` which may be useful. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment