Scala 值类,用例 [英] Scala value class, use cases

查看:30
本文介绍了Scala 值类,用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 value class 在 Scala 中在编译器时内联操作.

I know value class in scala inline the operation at compiler time.

可能是这样

case class A(i: Int) extends AnyVal {
   def +(that: A) = A(this.i + that.i)
} 
A(1) + A(2) // After compile it equals to 1 + 2 

但这对我来说似乎没什么.

But It seems not a big deal to me.

它可能会提高性能,但是,

It might enhance performance but,

调用 this.i + that.i 似乎并不比 i + i

为什么我们需要 value class 在 Scala 和任何用例中???

Why we need value class in scala and any use cases???

推荐答案

为什么要将单个值包装到另一个类中?

一个重要的用例是类型安全.假设您有可以乘以货币的函数,如下所示:

One big use case is type safety. Let's say you have function that can multiply money, like so:

def multiply(factor: Int, amount: Int): Int = ???

这样做的问题是很容易混淆两个参数,从而错误地调用函数.使用值类,您可以创建一个 Money 类型并重新编写函数,如下所示:

The problem with this is that it would be very easy to confuse the two arguments and therefore call the function incorrectly. With values classes, you could create a Money type and re-write the function like so:

case class Money(amount: Int) extends AnyVal
def multiply(factor: Int, amount: Money): Money = ???

现在使用您的特殊 Money 类型,编译器会告诉您是否尝试以错误的顺序传递参数.

Now with your special Money type, the compiler will tell you if you try to pass arguments in the wrong order.

如果不是值类,人们可能会说在某些情况下增加的类型安全不值得性能损失.但是,对于值类,您没有运行时开销(尽管存在限制:http://docs.scala-lang.org/overviews/core/value-classes.html).

Were it not a value class, people may say that the added type safety is not worth the performance penalty in some cases. However with value classes, you have no runtime overhead (there are limitations though: http://docs.scala-lang.org/overviews/core/value-classes.html).

实现相同目标的另一种方法是在 scalaz 中取消装箱(无运行时开销)标记类型:http://eed3si9n.com/learning-scalaz/Tagged+type.html

An alternative to achieve the same goal are unboxed (no runtime overhead) tagged types in scalaz: http://eed3si9n.com/learning-scalaz/Tagged+type.html

请注意,例如,haskell 使用 newtype 来实现相同的想法:https://wiki.haskell.org/Newtype

Note that for example haskell uses newtype for the same idea: https://wiki.haskell.org/Newtype

这篇关于Scala 值类,用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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