简体   繁体   English

Scalaz中的标记类型(@@)比较

[英]Tagged Type (@@) Comparison in Scalaz

While playing with Scalaz.Tag , I found that an weird comparison result. 在玩Scalaz.Tag ,我发现比较奇怪的结果。

import scalaz._, Scalaz._, Tags._, syntax.tag._

test("Creating Tagged type") {
  sealed trait USD
  sealed trait EUR
  def USD[A](amount: A): A @@ USD = Tag[A, USD](amount)
  def EUR[A](amount: A): A @@ EUR = Tag[A, EUR](amount)

  val oneUSD = USD(1)
  2 * oneUSD.unwrap shouldBe 2

  def convertUSDtoEUR[A](usd: A @@ USD, rate: A)
                        (implicit M: Monoid[A @@ Multiplication]): A @@ EUR =
    EUR((Multiplication(usd.unwrap) |+| Multiplication(rate)).unwrap)

  convertUSDtoEUR(USD(1), 2) === EUR(2) // true
  convertUSDtoEUR(USD(1), 2) === USD(2) // true

  convertUSDtoEUR(USD(1), 2) shouldBe EUR(2) // true
  convertUSDtoEUR(USD(1), 2) shouldBe USD(2) // true
}

I would like to distinguish different sealed traits. 我想区分不同的密封特征。 Is this intended behavior of scalaz.Tag or am i missing something? 这是scalaz.Tag预期行为还是我错过了什么?


Updated 更新

I implemented =:= as I can't use scalaz === inside org.scalatest.FunSuite due to org.scalactic.TripleEqualSupport 我实现了=:= ,因为由于org.scalactic.TripleEqualSupport我无法在org.scalatest.FunSuite使用scalaz ===

trait FunTestSuite
  extends FunSuite
  with Matchers
  with BeforeAndAfterEach
  with BeforeAndAfterAll
  with TestImplicits

trait TestImplicits {
  final case class StrictEqualOps[A](val a: A) {
    def =:=(aa: A) = assert(a == aa)
    def =/=(aa: A) = assert(!(a == aa))
  }

  implicit def toStrictEqualOps[A](a: A) = StrictEqualOps(a)
}

// spec
convertUSDtoEUR(USD(1), 2) =:= EUR(2)
convertUSDtoEUR(USD(1), 2) =:= EUR(3) // will fail
convertUSDtoEUR(USD(1), 2) =:= USD(3) // compile error

You are using === and shouldBe from scalatest. 您正在使用===并且shouldBe来自scalatest。 They only check the runtime value, not the types (they delegate to == ). 他们只检查运行时值,而不检查类型(它们委托== )。 If you want to distinguish the type, you'll have to use === from scalaz. 如果要区分类型,则必须使用scalaz中的===

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM