How to limit scope of an import

Is there a way to limit the scope/visibility of an import?

For example, even thought it is not 100%, I wanted to define the following method, without using the fully qualified type of the encoding variable. encoding:java.nio.charset.Charset.

One way of course is to just import java.nio.charset.Charset at the same level as the method definition. The disadvantage of that is that it contaminates the name space at that level. Again, not the end of the world, but I would prefer to only import the names I need in the places I need them.

I tried putting the method definition and the import inside a locally{ .... }, but that changes the visibility of the methods being defined.

  def withOutputToString(f:(String=>Unit)=>Unit):String = {
    withOutputToString(f, java.nio.charset.StandardCharsets.UTF_8)
  }

  def withOutputToString(f:(String=>Unit)=>Unit,
                         encoding:java.nio.charset.Charset):String = {
    import java.io.{ByteArrayOutputStream, PrintWriter}
    val baos = new ByteArrayOutputStream()
    val pw = new PrintWriter(baos)
    var str = ""

    def printer(str: String): Unit = {
      pw.print(str)
    }

    try {
      f(printer)
      pw.flush()
      str = new String(baos.toByteArray, encoding)
    } finally pw.close()
    str
  }

If you are that picky about imports, you can just use the full path when creating new instances:

val baos = new java.io.ByteArrayOutputStream()
val pw = new java.io.PrintWriter(baos)

I don’t think what you’re asking for is possible, except if you would be willing to go as far as extracting withOutputToString to a separate trait so there would be no other definitions in the same immediate scope.

If you don’t want to import java.nio.charset.Charset because you already have a type Charset in scope you can use a renaming import.

import java.nio.charset.{Charset => NioCharset}