本文介绍了Scala 中的类型安全原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在我的 Scala 代码中有类型安全的原语子类",而没有装箱的性能损失(对于非常低延迟的应用程序).例如,像这样:

I'd like to have type-safe "subclasses" of primitives in my Scala code without the performance penalty of boxing (for a very low-latency application). For example, something like this:

class Timestamp extends Long
class ProductId extends Long

def process(timestamp: Timestamp, productId: ProductId) {
  ...
}

val timestamp = 1: Timestamp // should not box
val productId = 1: ProductId // should not box

process(timestamp, productId) // should compile
process(productId, timestamp) // should NOT compile

有一个 去年 Scala 用户邮件列表上的线程 似乎得出结论,没有拳击就不可能实现,但我想知道现在在 Scala 2.8 中是否可行.

There was a thread on the Scala User mailing list last year which seemed to conclude it wasn't possible without boxing, but I wonder if this is possible now in Scala 2.8.

推荐答案

这种事情可以通过插件来保证.毕竟,Scala 不受支持且不起作用的单位插件在阻止将距离添加到持续时间时做了类似的事情.

This kind of thing could be ensured by a plugin. The unsupported and not-working units plugin for Scala, after all, did something like it when it prevented distances to be added to durations.

这篇关于Scala 中的类型安全原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:14