を安全に使用する方法がいくつかありますOption
。含まれている値を取得する場合はfold
、getOrElse
またはパターン マッチングを使用することをお勧めします。
opt.fold { /* if opt is None */ } { x => /* if opt is Some */ }
opt.getOrElse(default)
// matching on options should only be used in special cases, most of the time `fold` is sufficient
opt match {
case Some(x) =>
case None =>
}
値を変更して、 から抽出せずに別の場所に渡したい場合は、、などをOption
使用でき、したがって for-comprehensions も使用できます。map
flatMap
filter / withFilter
opt.map(x => modify(x))
opt.flatMap(x => modifyOpt(x)) // if your modification returns another `Option`
opt.filter(x => predicate(x))
for {
x <- optA
y <- optB
if a > b
} yield (a,b)
または、副作用を実行したい場合は、使用できますforeach
opt foreach println
for (x <- opt) println(x)