shakedzy
shakedzy

Reputation: 2893

Scala: initializing a val in a trait based on user input

I have a trait in my project which I use as my configurations file, something like that:

trait config {
   val people = Seq("John","Jessie")
}

This trait is used with extends) in all my objects (except the main one). What I would like to do is to assign a different value to people based on the args received in my main function from the user, so I'll have something like:

trait config {
   val people = args.head match {
      case "A" => Seq("John","Jessie")
      case "B" => Seq("Bill","James","Brad")
      case _ => Seq("Jimmy")
 }}

Is there a way to do that?

Upvotes: 0

Views: 170

Answers (1)

Sascha Kolberg
Sascha Kolberg

Reputation: 7162

What you ask is possible:

trait config {
  app: App =>

  lazy val people = args.head match {
    case "A" => Seq("John","Jessie")
    case "B" => Seq("Bill","James","Brad")
    case _ => Seq("Jimmy")
  }
}

object Main extends App with config {
  people.mkString
}

or you can reduce the trait to make it work for other types than App.

trait config {
  protected def args: Array[String]

  lazy val people = args.head match {
    case "A" => Seq("John","Jessie")
    case "B" => Seq("Bill","James","Brad")
    case _ => Seq("Jimmy")
  }
}

However, as already pointed out, it is not a good pattern.

If you want to provide a system wide config you might want to have a look at Typesafe Config

Upvotes: 2

Related Questions