Type-safe Equal
Type-safe Equal
==
in Scala is not type safe so the following code can never be true
as their types are different but it has no compile-time error.
1 == "1" // always false, no compile-time error
just-fp
has Equal
typeclass with typeclass instances for value types (Byte
, Short
, Int
, Char
, Long
, Float
and Double
) as well as String
, BigInt
and BigDecimal
.
It also has Equal
typeclass instances for WriterT
, Writer
and EitherT
.
With just-fp
,
import just.fp.syntax._
// use triple equals from just-fp
1 === "1"
// error: type mismatch;
// found : String("1")
// required: Int
1 === 1
// res1: Boolean = true
"a" === "a"
// res2: Boolean = true
1 !== 1
// res3: Boolean = false
1 !== 2
// res4: Boolean = true
If it's a case class
the equals
of which can be used for equality check, NatualEqual
can be used.
e.g.)
final case class Foo(n: Int)
Foo(1) === Foo(1)
// error: value === is not a member of repl.MdocSession.App0.Foo
// object Foo {
// ^
This can be solved by NatualEqual.equalA[A]
.
import just.fp._, syntax._
final case class Foo(n: Int)
object Foo {
implicit val eqaul: Equal[Foo] = Equal.equalA[Foo]
}
Foo(1) === Foo(1)
// res8: Boolean = true
// Boolean = true
Foo(1) === Foo(2)
// res9: Boolean = false
// Boolean = false
Foo(1) !== Foo(1)
// res10: Boolean = false
// Boolean = false
Foo(1) !== Foo(2)
// res11: Boolean = true