sbtのプロジェクト作成からAkka Streamの触りまでをやってみた

  • scala version:2.12.3
  • sbt version:1.0.2

sbtプロジェクト作成する

sbt new sbt/scala-seed.g8 

name [Scala Seed Project]:と聞かれるのでプロジェクト名を入力します.

プロジェクトのディレクトリが作成されます.

build.sbtの依存関係にAkka Streamを追加する

import Dependencies._

lazy val root = (project in file(".")).
  settings(
    inThisBuild(List(
      organization := "com.example",
      scalaVersion := "2.12.3",
      version      := "0.1.0-SNAPSHOT"
    )),
    name := "Hello",
    // 以下のように変更(libraryDependenciesを変更)
    libraryDependencies ++= Seq(
        scalaTest % Test,
        "com.typesafe.akka" %% "akka-actor" % "2.5.6",
        "com.typesafe.akka" %% "akka-stream" % "2.5.6"
        )
  )

コードを変更する

プロジェクト作成時に作成されているHello.scalaを以下のように変更しました.

package example

import akka.stream._
import akka.stream.scaladsl._
import akka.actor.ActorSystem

object Hello extends Greeting with App {
  implicit val system = ActorSystem("QuickStart")
  implicit val materializer = ActorMaterializer()

  val source = Source[Int](1 to 5)
  val sink = Sink.foreach[Int](println)

  source
   .map(_ * 2)
   .runWith(sink)


  println(greeting)
}

trait Greeting {
  lazy val greeting: String = "hello"
}

以下のように出力されたら成功です.

hello
[debug]     Thread run-main-0 exited.
[debug] Waiting for thread QuickStart-akka.actor.default-dispatcher-2 to terminate.
2
4
6
8
10

参考にしました

adtech.cyberagent.io