SBTで自作のライブラリを作って、IntelliJで取り込む


自作ライブラリをSBTのプロジェクトで作成します

プロジェクト名は「my-utils」にしました

パッケージcom.example.nwtgckを作ります

パッケージcom.example.nwtgck内にUtils.scalaを作成します

Utils.scala
package com.example.nwtgck

/**
  * Created by nwtgck on 2016/03/05.
  */
object Utils {
  def sayHello(name: String): Unit = println(s"Hello ${name}!")
  def sayGoodbye(name: String): Unit = println(s"Goodbye ${name}!")
}

ターミナルを開き、プロジェクトのあるディレクトリ(今回はmy-utils)にcdしてからsbt publish-localします

$ cd ~/IdeaProjects/my-utils/
$ sbt publish-local
# publish-localすると以下のようなものが表示されます
[info] Loading global plugins from /Users/nwtgck/.sbt/0.13/plugins/project
[info] Loading global plugins from /Users/nwtgck/.sbt/0.13/plugins
[info] Loading project definition from /Users/nwtgck/IdeaProjects/my-utils/project
[info] Set current project to my-utils (in build file:/Users/nwtgck/IdeaProjects/my-utils/)
[info] Packaging /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/my-utils_2.11-1.0-sources.jar ...
[info] Main Scala API documentation to /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/api...
[info] Compiling 1 Scala source to /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/classes...
[info] Done packaging.
[info] Wrote /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/my-utils_2.11-1.0.pom
[info] :: delivering :: default#my-utils_2.11;1.0 :: 1.0 :: release :: Sat Mar 05 15:58:10 JST 2016
[info] delivering ivy file to /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/ivy-1.0.xml
model contains 5 documentable templates
[info] Main Scala API documentation successful.
[info] Packaging /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/my-utils_2.11-1.0-javadoc.jar ...
[info] Done packaging.
[info] Packaging /Users/nwtgck/IdeaProjects/my-utils/target/scala-2.11/my-utils_2.11-1.0.jar ...
[info] Done packaging.
[info] published my-utils_2.11 to /Users/nwtgck/.ivy2/local/default/my-utils_2.11/1.0/poms/my-utils_2.11.pom
[info] published my-utils_2.11 to /Users/nwtgck/.ivy2/local/default/my-utils_2.11/1.0/jars/my-utils_2.11.jar
[info] published my-utils_2.11 to /Users/nwtgck/.ivy2/local/default/my-utils_2.11/1.0/srcs/my-utils_2.11-sources.jar
[info] published my-utils_2.11 to /Users/nwtgck/.ivy2/local/default/my-utils_2.11/1.0/docs/my-utils_2.11-javadoc.jar
[info] published ivy to /Users/nwtgck/.ivy2/local/default/my-utils_2.11/1.0/ivys/ivy.xml
[success] Total time: 2 s, completed 2016/03/05 15:58:12

すると、$HOME/.ivy2/local/defaultmy-utilsディレクトリが作成されます

自作ライブラリ(my-utils)を使いたいプロジェクトをSBTのプロジェクト作成してbuild.sbtに以下を追加します

libraryDependencies ++= Seq(
  "default" %% "my-utils" % "1.0"
)

あとは「my-utils」を取り込むことができたので
import com.example.nwtgck.Utilsが使えるようになっています

試しに、Utils.sayHelloUtils.sayGoodbyeを使うと、

import com.example.nwtgck.Utils

/**
  * Created by nwtgck on 2016/03/05.
  */
object Main {
  def main(args: Array[String]) {
    Utils.sayHello("Jack")
    Utils.sayGoodbye("Jack")
  }
}

IntelliJのコンソールに"Hello Jack!"と"Goodbye Jack!"が表示されうまく実行できました

とても参考になったところ