Sunday, October 18, 2015

Enrich the List with safe tail and init operations

// scala code

object Test {
  // copy elements from a list to an array
  val x = new Array[Int](5)
  val y = List(1, 3, 5)
  y.copyToArray(x, 0, 2)
  x
  // does it have definite size?
  x.hasDefiniteSize
  y.hasDefiniteSize

  implicit class ListSafeTailInit[A](val list: List[A]) {
    def tailOption: Option[List[A]] = {
      if (list.isEmpty) None else Some(list.tail)
    }

    def initOption: Option[List[A]] = {
      if (list.isEmpty) None else Some(list.init)
    }
  }


  // safe head and tail
  List[Int]().headOption.getOrElse(-9)
  List[Int]().lastOption.getOrElse(-9)
  // List[Int]().tail // UnsupportedOperationException
  Nil.initOption // None
  List[Int]().tailOption // None
}

0 comments: