'2017/03/04'에 해당되는 글 1건

  1. 2017.03.04 [scala] List와 Array의 lift 메소드


스칼라의 리스트(또는 배열)에서 특정 index의 값을 얻을 수 있지만 없는 Index에 접근하면 에러가 발생한다. 


scala> List(8, 9, 10)(0)

res5: Int = 8


scala> List(8, 9, 10)(3)

java.lang.IndexOutOfBoundsException: 3

  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:65)

  at scala.collection.immutable.List.apply(List.scala:84)

  ... 48 elided




리스트(또는 배열)에서는 IndexOutOfBoundsException이 발생하지 않도록 Option을 리턴하는 lift를 제공한다. 


scala> List(8, 9, 10).lift

res0: Int => Option[Int] = <function1>


scala> List(8, 9, 10).lift(1)

res1: Option[Int] = Some(9)


scala> List(8, 9, 10).lift(2)

res2: Option[Int] = Some(10)


scala> List(8, 9, 10).lift(3)

res3: Option[Int] = None


scala> List(8, 9, 10).lift(4)

res4: Option[Int] = None






만약 None이라도 getOrElse를 통해 값을 얻을 수 있다.


scala> List(8, 9, 10).lift(10).getOrElse(0).toInt

res10: Int = 0


scala> List(8, 9, 10).lift(1).getOrElse(0).toInt

res11: Int = 9





리스트(또는 배열)의 lift를 따로 올라가면 다음과 같다. PartialFunction이다. 


trait PartialFunction[-A, +B] extends (A => B) {
...

/** Turns this partial function into a plain function returning an `Option` result.
* @see Function.unlift
* @return a function that takes an argument `x` to `Some(this(x))` if `this`
* is defined for `x`, and to `None` otherwise.
*/
def lift: A => Option[B] = new Lifted(this)


PartialFunction[A, B]라 가정하면 PartialFunction에서 A타입을 받고 B 타입으로 올리는(lift)한다는 의미가 있다.



scala> val test: PartialFunction[Int, Int] = { case i if i == 0 => 0 ; case _ => -1}

test: PartialFunction[Int,Int] = <function1>


scala> test.lift(0)

res15: Option[Int] = Some(0)


scala> test.lift(11)

res16: Option[Int] = Some(-1)



Posted by '김용환'
,