简体   繁体   中英

Scala constructor how to convert this in Scala language

Hi I need help how to convert this in Scala with two constructor.

public class Configure {
  private final Config config;

  public Configure(String confFileName) {
    config = ConfigFactory.load(confFileName);
  }

  public Configure() {
    config = ConfigFactory.load();
  }

  public String getString(String name) {
    return config.getString(name);
  }
}
class Configure(private val config :Config) {
  def this()                     = this(ConfigFactory.load())
  def this(confFileName :String) = this(ConfigFactory.load(confFileName))
}

In Scala you would typically do this using a companion object:

class Configure private (config: Config) {
  def configString(name: String) = config.getString(name)
}

case object Configure {
  def apply(confFileName: String ) =
    new Configure(ConfigFactory.load(confFileName))

  def apply() =
    new Configure(ConfigFactory.load())
}

This nicely separates the behaviour of the class from the different ways of creating it.

[ I renamed getString because "getters" don't usually begin with get in Scala, they are just the name of the value being retrieved. ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM