scala에서 삼항 연산자 쓰기.

in #scala8 years ago

scala를 쓰면서 가장 불편했던 것은 삼항 연산자가 없다는것이다.

그래서 이를 좀 편하게 하기 위한 고민을한 결과 implicit method를 활용하면 좀 간편히 작성이 가능할 것 같았다.

val age = 5
val amIYoung = if( age < 10) "yes" else "no"

위와 같은 코드를 좀 더 줄이고 싶었다.

package utils

object ExtraOperator {
  class TernaryOperator[T](val trueVal: T, val falseVal: T) {
    def ?:(condition: => Boolean): T = if (condition) trueVal else falseVal
  }
  implicit def tupleToTernaryOperator[T](t: (T, T)) = new TernaryOperator(t._1, t._2)
}

코드를 설명해보자.

implicit def tupleToTernaryOperator[T](t: (T, T)) = new TernaryOperator(t._1, t._2)
  • Tuple2TernaryOperator로 암묵변환해주는 메소드이다.
def ?:(condition: => Boolean): T = if (condition) trueVal else falseVal
  • scala에 operator를 마음데로 넣을수 없으니 비스무리하게 생긴 method를 만들어준다. 인자로 Boolean을 반환하는 function parameter를 받아서 해당 parameter가 참이면 trueVal을 거짓이면 falseVal을 반환하는 method이다.

이렇게 준비했으면 이제 사용해보자.

import ExtraOperator._

val age = 5
val amIYoung = ("yes","no").?:(age < 10)

비록 import를 해야지만 사용가능하지만 Tuple2를 이용하여 조금은 더 간단히 구현해 보았다.

Sort:  

와우~ 스팀잇에도 프로그래밍 자료가 있네요.

Congratulations @castor.kim! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

3 years on Steem - The distribution of commemorative badges has begun!
Happy Birthday! The Steem blockchain is running for 3 years.
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.05
TRX 0.33
JST 0.078
BTC 63144.83
ETH 1685.61
USDT 1.00
SBD 0.39