-5

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);
  }
}
jwvh
  • 50,871
  • 7
  • 38
  • 64
BBAH
  • 46
  • 1
  • 6

2 Answers2

1
class Configure(private val config :Config) {
  def this()                     = this(ConfigFactory.load())
  def this(confFileName :String) = this(ConfigFactory.load(confFileName))
}
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • 1
    Strictly speaking, the primary constructor should be private as well for equivalence with Java. – Alexey Romanov Feb 20 '19 at 08:02
  • Why use `private val config` rather than just `config`? What is the advantage of making it a private member rather than just a constructor parameter? – Tim Feb 20 '19 at 14:50
1

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. ]

Tim
  • 26,753
  • 2
  • 16
  • 29