【Scala】SBT ~ 引数設定の仕方 ~

■ はじめに

小ネタ。

https://dk521123.hatenablog.com/entry/2023/08/01/004207

でやった「sbt run による引数設定の仕方」を分冊。
(見つけづらかったので)

目次

【1】sbt run
 1)引数を設定するための構文
 2)コマンド例
【2】build.sbt に独自の引数を追加
 1)構文
 2)サンプル

【1】sbt run

1)引数を設定するための構文

# "run xxx" のようにする
sbt "run --<Key1> <Value1> ..."

2)コマンド例

sbt "run --output Hello --intValue 100"

【2】build.sbt に独自の引数を追加

* System.getProperty() で取得
* sbt "-D<Key>=<Value> ..." で指定

1)構文

build.sbt

val <Value> = System.getProperty("<Key>", "<DaultValue>")

2)サンプル

build.sbt

val projectName = "my.proj"
val organization = "my.org"
scalaVersion := "2.12.15"

val echoTask = taskKey[Unit]("For logging...")
val isSomething = System.getProperty("isSomething", "false")
lazy val root = (project in file(".")).
  settings(
    name := "project-name",
    version := "1.0",
    echoTask := {
      println()
      println("*********************")
      if (isSomething.equals("true"))
        println(s"Hello, world!! ${name.value} - ${version.value}")
      else
        println(s"Hi, world!! ${name.value} - ${version.value}")
      println("*********************")
      println()
    }
  )

出力結果例1

$ sbt "-DisSomething=true echoTask"  
[info] welcome to sbt 1.8.2 (Oracle Corporation Java 11)
[info] loading settings for project sample-build-build from metals.sbt,plugins.sbt ...
...

*********************
Hello, world!! project-name - 1.0
*********************

[success] Total time: 0 s, completed 2023/08/28 15:50:22

出力結果例2

$ sbt "-DisSomething=false echoTask"  

*********************
Hi, world!! project-name - 1.0
*********************

補足:指定の順番

# エラーになる
$ sbt "echoTask -DisSomething=false"

[error] Expected whitespace character
[error] Expected '/'
[error] echoTask -DisSomething=false
[error]          ^

関連記事

Scala ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/03/10/193805
Scala ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/03/12/184331
SBT ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/03/22/000000
SBT ~ 設定の切替 ~
https://dk521123.hatenablog.com/entry/2023/08/28/165323
Apache Flink ~ 引数の扱い / ParameterTool ~
https://dk521123.hatenablog.com/entry/2023/08/01/004207