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
}