scala에서 삼항 연산자 쓰기.
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)
Tuple2를TernaryOperator로 암묵변환해주는 메소드이다.
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를 이용하여 조금은 더 간단히 구현해 보았다.
와우~ 스팀잇에도 프로그래밍 자료가 있네요.
Congratulations @castor.kim! You received a personal award!
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:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!