Scalaスケーラブルプログラミング読書メモ2
クラスパラメータ
クラス名の直後に書くコンストラクタを基本コンストラクタと呼び,基本コンストラクタの引数をクラスパラメータという.
class Rational(n: Int, d: Int)
事前条件チェック
require
を使うと,引数に渡される値に制限を設けることができる.
class Rational(n: Int, d: Int){ require(d != 0) override def toString = n + "/" + d }
クラスにおけるvar
, val
の可視性
class Num(n: Int) // private class Num(val n: Int) // public, valなのでイミュータブル class Num(var n: Int) // public, varなのでミュータブル
補助コンストラクター
class Rational(n: Int, d: Int){ def this(n: Int) = this(n, 1) }
リテラル識別子
識別子とは,変数名・関数名・クラス名などに用いられるもの.リテラル識別子とは,バッククォートで囲まれた任意の文字列.リテラル識別子の考え方は,バッククォートにどんな文字列をいれてもランタイムに識別を受付させようというもの.
case class `Rational`(n: Int, d: Int){ require(d != 0) override def toString = n + "/" + d } val r = `Rational`(3, 4) println(r.`toString`)
for式
// yield val evens = for(n <- (1 to 10) if n % 2 == 0) yield n println(evens) // フィルタリング for(n <- (1 to 10) if n % 2 == 0){ println(n) } // 複数フィルター for(n <- (1 to 10) if n % 2 == 0 if 3 < n )println(n) // 入れ子,中間結果の束縛 for( file <- filesHere if file.getName.endsWith(".scala"); line <- fileLines(file) trimmed = line.trim if trimmed.matches(pattern) ) println(file + ": " + trimmed)
関数のプレースホルダー構文
// コンパイラーが十分な型情報を持っていない時の対策 val f = (_: Int) + (_: Int) println(f(3, 4))