隐式类是否应该始终扩展AnyVal? [英] Should implicit classes always extend AnyVal?
问题描述
说我在写扩展方法
implicit class EnhancedFoo(foo: Foo) {
def bar() { /* ... */ }
}
您应该始终在类定义中包含extends AnyVal
吗?在什么情况下,您不想将隐式类设为值类?
Should you always include extends AnyVal
in the class defininition? Under what circumstances would you not want to make an implicit class a value class?
推荐答案
让我们看看列出了针对值类的限制,并考虑何时可能不适合隐式类:
Let's look at the limitations listed for value classes and think when they may not be suitable for implicit classes:
-
必须仅具有一个主要构造函数,该构造函数仅具有一个公共的val参数,其类型不是值类."因此,如果要包装的类本身是值类,则不能使用
implicit class
作为包装器,但是可以这样做:
"must have only a primary constructor with exactly one public, val parameter whose type is not a value class." So if the class you are wrapping is itself a value class, you can't use an
implicit class
as a wrapper, but you can do this:
// wrapped class
class Meters(val value: Int) extends AnyVal { ... }
// wrapper
class RichMeters(val value: Int) extends AnyVal { ... }
object RichMeters {
implicit def wrap(m: Meter) = new RichMeter(m.value)
}
如果包装器也具有隐式参数,则可以尝试将其移至方法声明. IE.代替
If your wrapper has implicit parameters as well, you can try to move them to the method declarations. I.e. instead of
implicit class RichFoo[T](foo: Foo[T])(implicit ord: Ordering[T]) {
def bar(otherFoo: Foo[T]) = // something using ord
}
你有
implicit class RichFoo[T](foo: Foo[T]) extends AnyVal {
def bar(otherFoo: Foo[T])(implicit ord: Ordering[T]) = // something using ord
}
可能没有专门的类型参数."在包装本身具有专用类型参数的类时,您可能希望包装器是专用的.
"may not have specialized type parameters." You may want the wrapper to be specialized when wrapping a class which itself has specialized type parameters.
此外,使隐式类成为值类可能会使用反射更改代码的某些行为,但反射通常不应看到隐式类.
In addition, making your implicit class a value class could possibly change some behavior of code using reflection, but reflection shouldn't normally see implicit classes.
如果您的隐式类确实满足所有这些限制,那么我就不会想到不将其设为值类的原因.
If your implicit class does satisfy all of those limitations, I can't think of a reason not to make it a value class.
这篇关于隐式类是否应该始终扩展AnyVal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!