irrelevantUser
irrelevantUser

Reputation: 1322

Import Scala object based on value of commandline argument

Lets say I have the following structure:

src
 - main 
  - scala
   - model
     - One.scala 
     - Two.scala
   - main
     - Test.scala

where Test.scala extends App and takes in a parameter:

object Test extends App {

val param: String = args.head  

// Based on param, I want to use either One or Two?

}
// sbt run Two

How do i use definitions in either One.scala or Two.scala depending on the runtime value of param.

Appreciate any/all inputs..

Upvotes: 1

Views: 95

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Make sure that One and Two share some common interface, choose the instance of this interface at runtime, then import the members of the instance:

trait CommonInterface {
  def foo(): Unit
}

object One extends CommonInterface { def foo() = println("1") }
object Two extends CommonInterface { def foo() = println("2") }

object Main extends App {
  // check args etc...
  val ci = if (args(0) == "one") One else Two
  import ci._
  // do something with `foo` here
  foo()
}

Upvotes: 3

Related Questions