Search code examples
scalavisibilitynamed-parametersvalue-class

Value classes introduce unwanted public methods


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
}

This introduces an unwanted symbol i:

4.i   // arghh....

That stuff appears both in the scala docs and in the IDE auto completion which is really not good.

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?)


EDIT:

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
}

Solution

  • 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
    }