值类引入不需要的公共方法 [英] Value classes introduce unwanted public methods
问题描述
查看我的库的一些 Scala 文档,在我看来,值类存在一些不需要的噪音.例如:
Looking at some scala-docs of my libraries, it appeared to me that there is some unwanted noise from value classes. For example:
implicit class RichInt(val i: Int) extends AnyVal {
def squared = i * i
}
这引入了一个不需要的符号i
:
This introduces an unwanted symbol i
:
4.i // arghh....
这些东西出现在 scala 文档和 IDE 自动完成中,这真的很糟糕.
That stuff appears both in the scala docs and in the IDE auto completion which is really not good.
那么...关于如何缓解这个问题的任何想法?我的意思是你可以使用 RichInt(val self: Int)
但这并没有让它变得更好(4.self
,wth?)
So... any ideas of how to mitigate this problem? I mean you can use RichInt(val self: Int)
but that doesn't make it any better (4.self
, wth?)
编辑:
在下面的例子中,编译器是否擦除了中间对象?
In the following example, does the compiler erase the intermediate object, or not?
import language.implicitConversions
object Definition {
trait IntOps extends Any { def squared: Int }
implicit private class IntOpsImpl(val i: Int) extends AnyVal with IntOps {
def squared = i * i
}
implicit def IntOps(i: Int): IntOps = new IntOpsImpl(i) // optimised or not?
}
object Application {
import Definition._
// 4.i -- forbidden
4.squared
}
推荐答案
在 Scala 2.11 中,您可以将 val 设为私有,从而解决此问题:
In Scala 2.11 you can make the val private, which fixes this issue:
implicit class RichInt(private val i: Int) extends AnyVal {
def squared = i * i
}
这篇关于值类引入不需要的公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!