yoshikit1996’s diary

日々勉強したことの備忘録です。

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))

その他

  • Scalaの定数はUpperCamelCase
  • 暗黙の型変換 `implicit def intToRational(x: Int) = Rational(x)
  • スコープの内側の変数を外側の変数を見えなくすることをシャドウイングという
  • 副作用があるようなメソッドはメソッド名に空括弧をつける習慣がある.def width(): Int
  • 名前渡しパラメータ.myAssert(predicate: => Boolean)という関数を定義してmyAssert(3 < 5)とした場合,3 < 5は関数呼び出し後に評価される.