Scala equality with type checking?

2020-06-08 23:20发布

问题:

Is there a uniform method to perform equality with type checking? Unfortunately

val objectA:String = "test"
val objectB:Int = 2
objectA == objectB

the equality operator == doesn't complain if objectB is a Int while objectA is a String. I would need an operator like === that perform type checking as well (and I hope it is uniform to all scala obj). Does such operator exist?

回答1:

You need to look at scalaz's === for type-safe equals - it's implemented as type class there.

You can also watch talk by Heiko Seeberger, where he describes how it's implemented:

http://days2011.scala-lang.org/node/138/275

You can also find some examples here:

http://scalaz.github.com/scalaz/scalaz-2.9.1-6.0.4/doc.sxr/scalaz/example/ExampleEqual.scala.html#24187

(in the examples they are using method, but it's simply alias for ===)



回答2:

Scalaz provides such an operator.

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> 4 === "Scala"
<console>:14: error: type mismatch;
 found   : java.lang.String("Scala")
 required: Int
              4 === "Scala"
                    ^

scala> 4 === 4
res7: Boolean = true

scala> 4 === 5
res8: Boolean = false


回答3:

This is also provided by the ScalaUtils library:

import org.scalautils.TypeCheckedTripleEquals._

scala> "Scala" == Some("Scala")
res1: Boolean = false

scala> "Scala" === Some("Scala")
<console>:11: error: types String and Some[String] do not adhere to the type
  constraint selected for the === and !== operators; the missing implicit 
  parameter is of type org.scalautils.Constraint[String,Some[String]]
              "Scala" === Some("Scala")
                      ^


回答4:

scala dotty(aka scala 3) has a feature called Multiversal Equality which allows type safe equality.

Below is the dotty REPL example;

scala> val data1 = "string" 
val data1: String = "string"

scala> val data2 = Array(1, 2, 3, 4) 
val data2: Array[Int] = [I@86733

scala> val comparisonBool = data1 == data2 
1 |val comparisonBool = data1 == data2
  |                     ^^^^^^^^^^^^^^
  |    Values of types String and Array[Int] cannot be compared with == or !=

Dotty is a next generation compiler for Scala - http://dotty.epfl.ch/#getting-started

Note:

When will scala 3 come out?

The intent is to publish the final Scala 3.0 soon after Scala 2.14. At the current release schedule (which might still change), that means early 2020.