Scala、SBT、IntelliJ

まず始めに

IntelliJScalaプラグイン、SBTプラグインを入れておく。

とりあえず

参考: http://vyazici.blogspot.jp/2012/11/setting-up-scala-development.html

HelloWorldディレクトリ作成。

cd HelloWorld

build.sbt ファイル作成。
内容は以下。
Scalaのバージョンは2.10.0をインストールしているが、ここでは"2.9.2"指定のまま。

name := "ScalaHelloWorld"
 
version := "0.0.1"
 
scalaVersion := "2.9.2"
 
libraryDependencies += "org.scalatest" %% "scalatest" % "2.0.M1" % "test"

IntelliJプロジェクトを作成できるようにするため。
/project/plugins.sbt ファイル作成。
内容は以下。

resolvers += "Sonatype snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/"
 
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.2.0-SNAPSHOT")

cmdからsbtを実行。
sbtの中でgen-ideaを実行。

IntelliJからプロジェクトを開く。

src/main/scala/Main.scala ファイル作成。
内容は以下。

object Main {
  def main(args: Array[String]) {
    println("Hello, World!")
    println("# of arguments: %d" format count(args))
  }
 
  def count[T](it: Iterable[T]): Int = it.size
}

src/test/scala/MainSuite.scala ファイル作成。
内容は以下。

import org.scalatest.FunSuite
 
class MainSuite extends FunSuite {
  test("counting an empty collection") {
    assert(Main.count(Array[Int]()) == 0)
    assert(Main.count(Map()) == 0)
    assert(Main.count(Set()) == 0)
  }
 
  test("counting a non-empty collection") {
    assert(Main.count(Array(1)) == 1)
    assert(Main.count(Map(1 -> 1)) == 1)
    assert(Main.count(Set(1)) == 1)
  }
}

SBT ConsoleでStart SBTをクリックし、そのコンソール中で、
testと打てばテストできる。
runと打てば実行ができる。

package-distを使うためにはさらに一手間必要。

いちいち作るのも面倒なので

参考: http://xerial.org/scala-cookbook/recipes/2012/06/28/create-a-scala-project/

git clone git://github.com/xerial/scala-cookbook.git -b min-project default

このdefaultには手を加えず、プロジェクトディレクトリとしてmyprojectディレクトリを作成。
git initして、そこにdefaultディレクトリの中身を.gitを除いてコピーする。
その後、以下を実行。

cd ../myproject
sbt run
sbt gen-idea

IntelliJからプロジェクトを開く。

Build.scalaや、パッケージ設定を独自のものに変更した後、テストなどを行う。

SBT ConsoleでStart SBTをクリックし、そのコンソール中で、
testと打てばテストできる。
runと打てば実行ができる。
package-distと打てばtarget\distに配布形式でコンパイルされる。
(target/dist/bin/launchを実行する。ファイルの正体はシェルスクリプトなので適した環境で実行する。
./launchとすれば実行できる*1

*1:WindowsでやってるのでGit Bashから実行したりしてます