学んだことをなぐり書き


エントリーポイント

  • sample.scala
/**
 * mainという名前の Array[String] の引数があるメソッドを持つ object ならば
 * どれでもエントリーポイントになる。
 * 何個でも持つことでき切り替えて使うことが出来る。
 */
object A {
  def main(args: Array[String]) = println("A")
}

class Base(s: String) {
  def main(args: Array[String]) = println(s)
}

object B extends Base("B")
scalac sample.scala
scala A
A
scala B
B

NotNull

// NotNull トレイトを mix-in すると null が入らないことを静的に保証する(コンパイル時にチェックしてくれる)ことが出来る。
var s1: String = "aiueo"
println(s1)
s1 = null
println(s1)

var s2: String with NotNull = "hoge"
// s2 = null <- error: type mismatch

class C extends NotNull
var c = new C
// c = null <- error: type mismatch
aiueo
null

引数がタプルだけの場合、括弧() は省略可能

object Main {
  def tuple(pair: Pair[Int, String]) = println(pair)
  def tuple(tuple4: Tuple4[Int, String, Float, Int]) = println(tuple4)  

  def main(args: Array[String]) {
    // 引数がタプルだけの場合 ((tuple)) という記述は (tuple) という形に省略可能
    tuple((3, "hoge"))
    tuple(3, "hoge")

    // 別の数のタプルのオーバーロードも可能
    tuple(1, "a", 3.14f, 100)
  }
}
(3,hoge)
(3,hoge)
(1,a,3.14,100)

メンバーのみ編集できます