Scalaz拆箱标签类型不会自动拆箱

问题描述:

阅读http://eed3si9n.com/learning-scalaz/Tagged+type.html和尝试的示例代码:据导游Scalaz拆箱标签类型不会自动拆箱

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,然而,在斯卡拉2.11.2我得到:

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 ([email protected]@[Double,KiloGram]) 
       2 * mass 
       ^

2 * mass.asInstanceOf[Double] 

工作得很好。

这是一个2.10 vs 2.11的东西,或者我失去了一些东西?如果我不能像这样(不再)使用它们并且不得不求助于显式强制转换,那么unboxed标记类型的意义何在?

好的,事实证明这在Scalaz 7.1中被https://github.com/scalaz/scalaz/pull/693改变了。

基本上旧的实现标签类型的竟然是不够安全,于是有人提出,这样的标签类型的明确解包将在“标签”的内容之前有必要可以使用:

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

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

+1

我刚刚发布了该页面的更新版本(http://eed3si9n.com/learning-scalaz/Tagged+type.html)。 js1972给了我一个公共关系来解决这个问题,但到现在我还没有到处解决问题。 – 2014-10-02 11:14:47

+0

是不是应该是'2 * Kilogram.unwrap(mass)'tho?你目前有'Tag.unwrap(mass)'。 – 2014-10-02 12:44:06

+0

是更有意义的。 – 2014-10-02 14:51:01