Scala:Option
값이 있거나 또는 없거나 한 상태를 나타낼 수 있는 타입이다.
About
값이 담겨져 있는 Option
의 하위 타입은
- 값이 담겨져 있다면
Some[T]
이며, - 값이 없으면
None
이다.
Option
은 Scala:Try, Scala:Future 등과 함께 대표적인 모나딕컬렉션 이다.
When to use it?
보통 Option 을 떠올리면 2가지를 생각해야한다.
- null 을 안전하게 대체하기 위해 만들어진 것.
- 사용자에게 주의를 다시 한번 당부하는 것으로, null 예외가 발생할 확률을 없앤다.
- 연속체인에서 안정적으로 사용하기 위한 것
- 연속으로 계산되는 상황에서 안정적으로 실행된다. 즉 중간에 문제가 생기는것을 방어한다. 주의 할 것은 방어가 되는 함수는 따로 있다는 것이며 아래 표에서 자세히 설명된다.
Methods
- get
- Option 에서 값 가져오기
- isDefined
- #Some 인지 확인한다.
- isEmpty
- #None 인지 확인한다.
- getOrElse
- 값이 있으면 사용하고, 없으면 인자로 넘긴 아규먼트를 사용한다.
패턴 매칭으로 사용하기
def testOption(o : Option[Int]) = {
val result = o match {
case Some(n) => n
case None => "nothing"
}
}
Some
/** Class `Some[A]` represents existing values of type
* `A`.
*
* @author Martin Odersky
* @since 1.0
*/
@SerialVersionUID(1234815782226070388L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class Some[+A](@deprecatedName('x, "2.12.0") value: A) extends Option[A] {
def isEmpty = false
def get = value
@deprecated("Use .value instead.", "2.12.0") def x: A = value
}
None
/** This case object represents non-existent values.
*
* @author Martin Odersky
* @since 1.0
*/
@SerialVersionUID(5066590221178148012L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}