Scalaz拆箱标记的类型不会自动拆箱 [英] Scalaz unboxed tagged type not automatically unboxed

查看:99
本文介绍了Scalaz拆箱标记的类型不会自动拆箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 http://eed3si9n.com/learning-scalaz/Tagged+type.html 并尝试示例代码:

import scalaz._; import Scalaz._

sealed trait KiloGram
def KiloGram[A](a: A): A @@ KiloGram = Tag[A, KiloGram](a)
val mass = KiloGram(20.0)
2 * mass

根据指南,应该产生40.0,但是,在Scala 2.11.2上我得到:

according to the guide, should yield 40.0, however, on Scala 2.11.2 I get:

scala> 2 * mass
<console>:17: error: overloaded method value * with alternatives:
  (x: Double)Double <and>
  (x: Float)Float <and>
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (scalaz.@@[Double,KiloGram])
              2 * mass
                ^

2 * mass.asInstanceOf[Double]

工作正常.

是2.10 vs 2.11,还是我缺少什么?如果我不能再使用这样的无框标记类型,又不得不求助于显式转换,那又有什么意义呢?

Is that a 2.10 vs 2.11 thing or I'm missing something? What is the point of unboxed tagged types if I can't use them like this (anymore) and have to resort to explicit casts?

推荐答案

好,事实证明,这在Scalaz 7.1中由进行了更改https://github.com/scalaz/scalaz/pull/693 .

OK, turns out this was changed in Scalaz 7.1 by https://github.com/scalaz/scalaz/pull/693.

基本上,标记类型的旧实现不够安全,因此它被制成为在可以使用标记"的内容之前,有必要对标记类型进行显式拆包:

Basically the old implementation of tagged types turned out as not safe enough, so it was made so that an explicit unwrap of the tagged type would be necessary before the contents of the "tag" could be used:

scala> trait Kg
scala> val Kg = Tag.of[Kg]
scala> val mass = Kg(15.0)
scala> 3 * Kg.unwrap(mass)
res0: Double = 45.0

感谢#scalaz上的S11001001,ceedubs,tpolecat和adelbertC指出了这一点.

Thanks to S11001001, ceedubs, tpolecat and adelbertC on #scalaz for pointing this out.

这篇关于Scalaz拆箱标记的类型不会自动拆箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆