Java에서 항상 우리가 하던대로 코딩하면 아래와 같이 나온다.
Customer customer = Customers.findById(1234); return customer.getAccount(SOME_ACCOUNT).getLastInterest.getAmount
하지만 그냥 위와 같이 쓰게 되면 nullPointException에서 자유로울수 없기 때문에 보통 아래와 같이 사용한다.
Customer customer = Customers.findById(1234);
if(customer !=null){
    if(customer.getAccount(SOME_ACCOUNT)!=null){
        if(customer.getAccount(SOME_ACCOUNT).getLastInterest!=null){
            return customer.getAccount(SOME_ACCOUNT).getLastInterest.getAmount
        }
    }
}
return null;
scala라고 다를 것이 없다. 똑같이 null check를 java에서 하던방식으로 그대로 하게 되면 아래와 같이 UGLY하게 보이게 된다.
val customer = Customers findById 1234
if(customer!=null){
    val account = customer.account(SOME_ACCOUNT)
    if(account!=null){
        val interest = account.getLastInterest
        if(interest!=null){
             interest.amount
        else
            null
    } else
        null
}else
    null
scala에서는 값이 있거나 또는 없거나 한 상태를 나타낼 수 있는 타입이 있다.
그 타입은 Option이다.
Use scala option
Option은 null에 대해 안전하게 대처할 수 있도록 설계되어 있고, 제공하는 함수를 통해 짧은 코드로 효율적인 nullPointException을 제거 할 수 있다. 아래는 Option이 어떻게 이루어져 있는지 개략적으로 볼 수 있다.
sealed trait Option[A] case class Some[A](a: A) extends Option[A] case class None[A] extends Option[A]
아래와 같이 Option을 직접적으로 선언도 가능하다.
val o = Some(3) // o : Option[Int] = Some(3) val n = None // n : None.type = None val oo = Option(3) // oo : Option[Int] = Some(3) val nn = Option(null) // nn : Option[Null] = None
Example
아래와 같이 Option에서 제공하는 추출함수를 통해 null에 대한 처리를 직관적으로 할 수 있다.
추출함수로는 fold, getOrElse, orElse 그리고 위에서 사용한 match expression이 있다.
val customer = Customers findById 1234 match {
    case Some(customer) => customer
    case None => new Customer()
}
val customer = Customers.findById(1234) getOrElse new Customer()
반응형
    
    
    
  'Programming Language > Java & Scala' 카테고리의 다른 글
| Java 8 에서 사라진 maxPermSize, PermSize을 대체하는 옵션? (0) | 2019.01.01 | 
|---|---|
| Java 시큐어 코딩 - 공격 종류 및 해결방안 (0) | 2018.11.23 | 
| Java 시큐어 코딩 - 개론 및 보안사례 (0) | 2018.11.22 | 
| Intellij에서 scala와 sbt를 사용시 반드시 알아야할 3가지 (0) | 2018.10.16 | 
| [Groovy]배열 종류 및 사용법 (2) | 2018.03.12 | 
| [Groovy]변수 선언하기 및 변수 종류 (0) | 2018.03.12 |