Are there any triple equals === methods outside of Cats in Scala?

1.2k views Asked by At

I have spent a while searching on Google for a non-Cats triple equals method, but can't find anything apart from Scalaz. Unfortunately, I have been unable to work out the import for === in this library.

Can someone help, many thanks.

4

There are 4 answers

0
Mario Galic On BEST ANSWER

Regarding scalaz try

import scalaz._
import Scalaz._

42 === "hello" // error: type mismatch; found: String("hello") required: Int

where

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.28"
2
Krzysztof Atłasik On

Another library that provides === is scalactic, which is basically a set of utilities used by ScalaTest, which are packaged as a separate lib.

import org.scalactic._
import TypeCheckedTripleEquals._

"Hello" === "Hello" //true
1 === "Hello" //won't compile

you can also "configure" how your equality is being resolved with implicits:

import org.scalactic._
import TripleEquals._
import StringNormalizations._
import Explicitly._

implicit val strEquality = decided by defaultEquality[String] afterBeing lowerCased

"Hello" === "hello"                           // true
"normalized" === "NORMALIZED"                 // true
1
sachav On

If all you need is ===, you could very easily mimic the behaviour from Cats with your own function:

implicit class AnyWithTripleEquals[T](a: T) {
  def ===(b: T): Boolean = a equals b
}

/*
scala> "2" === "3"
res0: Boolean = false

scala> "2" === 3
<console>:13: error: type mismatch;
 found   : Int(3)
 required: String
       "2" === 3
*/
0
Mateusz Kubuszok On

Of the top of my head other libraries that use === are e.g.:

but it isn't the same use case as in Cats/Scalaz.

If you want to use it in Cats you need:

  • syntax - import cats.syntax.eq._ or import cats.syntax.all._ or import cats.implicits._ (if you duplicate import of syntax, Scala won't be able to resove it)
  • instance - if you compare 2 A you need an implicit instance of cats.Eq[A]. instances for Lists, Maps etc. can be found in cats.instances.list._, cats.instances.map._, cats.instances.all._ or cats.implicits._ (same rule as above). There should be instances for all "normal" types but if you have your own, you need to either provide Eq instance on your own or derive it with something like Kittens.

If you are missing some implicit (or if some implicit is ambiguous, because you imported the same things from 2 different places) the syntax won't work.

Same thing about Scalaz though imports and type classes will have other names.

If you don't mind some performance penalty (caused by isInstanceOf inside equals) and lack of flexibility regarding the definition of equality check, you can use @sachav's solution.