Export and visibility

Every member has a visibility, and the Scala keywords narrow it instead of widening it: private and protected are the Java ones, and a qualified form scopes a member to a package or a class. export is the other direction: it makes a member of a field part of the enclosing object, so a wrapper can offer a service without a method of its own for each one.

export

Service keeps a private logger and exports two of its methods. The caller sees service.warn and cannot see the logger, which is the point: the field is an implementation detail, the two methods are the service:

export.scala

class Logger: def info(message: String): Unit = println(s"INFO $message") def warn(message: String): Unit = println(s"WARN $message") class Service: private val logger = Logger() export logger.{info, warn} def run(): Unit = info("running") @main def exportExample(): Unit = val service = Service() service.run() service.warn("careful")

scala-cli run --server=false export.scala

INFO running
WARN careful

An export may also rename: export logger.{info as log} gives the member another name in the wrapper. The mechanism is how a façade over a library is written without one forwarding method per call, and the compiler keeps the types of the exported members.

private, protected and a package

private is visible in the class and its companion, protected in the subclasses, and a qualifier narrows either one to a package. The program below puts the object and its client in one package, and private[demo] is what lets the client call the method while the value stays private:

demo.scala

package demo object Secrets: private val key = "hidden" private[demo] def reveal: String = key class Client: def show: String = Secrets.reveal @main def visibility(): Unit = println(new Client().show)

scala-cli run --server=false demo.scala

hidden

key is private to the object, so only reveal can read it; reveal itself is private to the package demo, so any class of that package may call it and a class outside it may not. The form private[this] of Scala 2 is gone: a plain private means the same, and the compiler warns about the old spelling.

Related

Article author: Arthur Isaev