scala 構文4

パターンマッチ

case class Point(x: Int, y: Int)

object MyApp {

  def main(args: Array[String]): Unit = {

   var points = List(
    Point(5, 3),
    Point(0, 0),
    Point(3, 4)
   )
   points.foreach(_ match{
    case Point(0, 0) => println("original")
    case Point(5, _) => println("right edge")
    case Point(x, y) => println(s"$x:$y")
   })

  }

}

option型のエラー処理

object MyApp {

  def main(args: Array[String]): Unit = {
  val scores = Map("yoshimoto" -> 55, "kimoto" -> 65)
  scores.get("tanaka") match {
   case Some(v) => println(v)
   case None => println("key not found")
  }
  }

}

Eitherによるエラー処理

object MyApp {

 // Error Either - right, left

  def div(a: Int, b: Int): Either[String, Int] = {
  if (b == 0) Left("Zero div error!")
  else Right(a / b)
  }
  def main(args: Array[String]): Unit = {

   div(10, 2) match {
   case Right(n) => println(n)
   case Left(s) => println(s)
   }

  }

}

scala 構文3

関数オブジェクト

object MyApp{

  def multi(a: Int, b: Int) = a * b
  val multFunc = (_: Int) * (_: Int)

  def main(args: Array[String]): Unit = {
    println(multFunc(3, 5))
  }

}

関数のカリー化

object MyApp {

  def main(args: Array[String]): Unit = {
    // 関数のカリー化
    val multFunc = (a: Int, b: Int) => a * b
    val multFuncCurried = (a: Int) => ((b: Int) => a * b)

    // println(multFunc(3, 5))
    // println(multFuncCurried(3)(5))

    val double = multFuncCurried(2)
    val tripple = multFuncCurried(3)

    println(double(5)) // 10
    println(tripple(5)) // 15
  }

}

関数の部分適用

object MyApp {

  def msg(from: String, to: String, text: String) = s"($from -> $to): $text"

  def main(args: Array[String]): Unit = {

  val msgToKouda = msg(_: String, "Kouda", _:String)
  println(msgToKouda("yamagata", "OK!"))
  println(msgToKouda("yoshimoto", "Great"))
  println(msgToKouda("eto", "good"))

  }

}

タプル

object MyApp {

  def swap(a: Int, b: Int) = (b, a)

  def main(args: Array[String]): Unit = {
  // val data = (12, "igarashi", 52.6)
  // println(data._1)
  // println(data._2)
  // println(data._3)
  val (x, y) = swap(32, 55)
  print(x)
  print(y)
  }

}

List

object MyApp {

  def main(args: Array[String]): Unit = {
    // val scores = List(200, 300, 400)
    val scores = 200 :: 300 :: 400 :: Nil
   println(scores.length)
   println(scores.isEmpty)
   println(scores.tail)
   println(scores.head)
   println(scores(1))
  }

}

set

object MyApp {

  def main(args: Array[String]): Unit = {
    //val answers = Set(5, 3, 4, 5)
    //println(answers)
    // println(answers.container(3))
    //println(answers(3))

    val set1 = Set(1, 3, 5, 8)
    val set2 = Set(3, 5, 7, 9)

    println(set1 & set2)
    println(set1 | set2)
    println(set1 &~ set2)

  }

}

map

object MyApp {

  def main(args: Array[String]): Unit = {

   val sales = Map("yoshida" -> 200, "kimura" -> 500)
   println(sales("yoshida"))
   println(sales("kimura"))
   println(sales.contains("murata"))

  }

}

mutable

    val scores = scala.collection.mutable.Map("ito" -> 55, "yamamoto" -> 65)
   scores("ito") = 60

map, filter, foreach

object MyApp {

  def main(args: Array[String]): Unit = {
    val prices = List(52.3, 48.6, 32.8)

    prices.map(_ * 1.08).filter(_ > 50).foreach(println)

  }

}

scala 構文2

object MyApp{

  def main(args: Array[String]): Unit = {
  // for(ジェネレータ ※変数<-データ集合)
  for (i <- 0 to 3; j <- 0 to 3 if i != j) println(s"i, $j")

  }

}

method

object MyApp{

  // method

  def sayHi: String = {
      // println("hi!")
      "hi!"
  }

  def main(args: Array[String]): Unit = {
    println(sayHi)

  }

}

メソッドの引数

object MyApp{

  def sayHi(name: String = "yokota", age: Int = 23): Unit = {
      println(s"hi! $name ($age)")
  }

  def main(args: Array[String]): Unit = {
    sayHi("bob", 35)
    sayHi("tom", 43)
    sayHi()
    sayHi(age = 18, name="jack")

  }

}

class

class User {
  val name = "my name"
  def sayHi() =  println("hi!")
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val user = new User
    println(user.name)
    user.sayHi()
  }

}

コンストラクタ引数

class User(_name: String) {
  val name = _name
  def sayHi() =  println("hi!" + this.name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val tom = new User("tom")
    println(tom.name)
    tom.sayHi()
  }

}

継承、override

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser(name: String, val age: Int) extends User(name) {
  def sayHello() =  println("hello!" + name + "(" + age  + ")")
  override def sayHi() = println("[admin] hi " + name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val bob = new AdminUser("bob", 23)
    println(bob.name)
    println(bob.age)
    bob.sayHi()
    bob.sayHello()
  }

}

package

package com.hpscript.model 

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser(name: String, val age: Int) extends User(name) {
  def sayHello() =  println("hello!" + name + "(" + age  + ")")
  override def sayHi() = println("[admin] hi " + name)
}

アクセス修飾子

class User {
  protected var name = "user"
  def sayHi() =  println("hi!" + this.name)
}

class AdminUser extends User {
  override def sayHi() = println("[admin] hi " + name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val user = new User
    val adminUser = new AdminUser
     // println(user.name)
    user.sayHi()
    adminUser.sayHi()
  }

}

object

object User {
 def getInfo() = println("User Object")
}

class User(val name: String) {
  def sayHi() =  println("hi!" + this.name)
}

object MyApp{
  def main(args: Array[String]): Unit = {
    User.getInfo()
  }

}

抽象クラス

abstract class User{
  def sayHi()
}

class Japanese extends User {
 def sayHi() = println("こんにちは")
}

class American extends User {
 def sayHi() = println("hello")
}

object MyApp{
  def main(args: Array[String]): Unit = {
   val aki = new Japanese
   val tom = new American
   aki.sayHi()
   tom.sayHi()
  }

}

trait

trait Printable {
 def print() = println("now printing ...")
}

trait Sharable {
 def share() = println("now sharing ...")
}

class User extends Printable with Sharable

object MyApp{
  def main(args: Array[String]): Unit = {
    val user  = new User
    user.print()
    user.share()
  }

}

型パラメータ

//class MyInt {
//  def getThree(i: Int): Unit = println(s"$i $i $i")
//}

class MyData[T]{
  def getThree(i: T): Unit = println(s"$i $i $i")
}

object MyApp{
  def main(args: Array[String]): Unit = {
    val i = new MyData[Int]
    i.getThree(5)
    val s = new MyData[String]
    s.getThree("hello")
  }

}

scala構文

変数

object MyApp{

  def main(args: Array[String]): Unit = {
   // 変数
   // - val:値の再代入ができない
   // - var:値の再代入ができる

   // val msg: String = "hello world";
   val msg = "hello world again"
    println(msg)
  }
}

データ型

// 整数 Byte Short Int Long
   val i = 5
   val l = 5555555555L
   val d = 32534.4
   val f = 234.34F
   val c = 'a' // 文字char
   val s = "Hello" // 文字列string
   var flag = true // Boolean
   val msg = "hello\n world again\t"
    println(msg)

四則演算

   // + - * / %
   val x = 10
   println(x / 3)
   println(x / 3.0)
   println(x % 3)

   var y = 6
   y += 10
   println(y)

   var s = "hello"
   println(s + "world")

   var flag = true
   println(!flag)

文字列

object MyApp{

  def main(args: Array[String]): Unit = {
   var name = "igarashi"
   var score = 55
   val height = 159.32

   println(s"name: $name, score: $score, height: $height")
   println(s"name: $name, score: ${score + 10}, height: $height")

   println(f"name: $name%s, score: $score%d, height: $height%f")
   println(s"name: $name%10s, score: $score%10d, height: $height%10f")
  }
}

条件分岐

object MyApp{

  def main(args: Array[String]): Unit = {
   val score = 85
   if (score > 80) println("Great!")
   else if (score > 60) println("Great!")
   else println("soso...")
  }
}

条件分岐 match

object MyApp{

  def main(args: Array[String]): Unit = {
   val signal = "red"
   var result = signal match {
    case "red" => "stop"
    case "blue" | "green" => "go"
    case "yellow" => "caution"
    case _ => "wrong signal"
   }
   println(result)
  }
}

while

object MyApp{

  def main(args: Array[String]): Unit = {
   var i = 0
   while (i < 10){
   println(i)
   i += 1
   }
  }
}

sbt 及び scalaのインストール

sbtのインストール

http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Linux.html

curl https://bintray.com/sbt/rpm/rpm | sudo tee /etc/yum.repos.d/bintray-sbt-rpm.repo
sudo yum install sbt

atomにもscala-formatのpackageをインストールしておきます。

sbt -> console でscalaのコマンドを試すことができます。

[vagrant@localhost scala]$ sbt
[info] Set current project to scala (in build file:/home/vagrant/scala/)
scala> 1 + 2
res0: Int = 3

scala> 2 + 2
res1: Int = 4

メモリが足りないと表示された場合は、sbt -mem 512でスタートさせます。

sbt -mem 512

ファイルは、src/main/scala/が推奨されています。
コンパイル実行は、sbt-> runとします。

object MyApp{

  def main(args: Array[String]): Unit = {
    println("hello world")
  }
}
[vagrant@localhost scala]$ sbt
[info] Set current project to scala (in build file:/home/vagrant/scala/)
> run
[info] Compiling 1 Scala source to /home/vagrant/scala/target/scala-2.11/classes...
[info] Running MyApp
hello world
[success] Total time: 20 s, completed 2016/11/21 16:55:04