Skip to content

Instantly share code, notes, and snippets.

@msbaek
Created June 5, 2015 05:50
Show Gist options
  • Save msbaek/19f487c569b18003a2e1 to your computer and use it in GitHub Desktop.
Save msbaek/19f487c569b18003a2e1 to your computer and use it in GitHub Desktop.
Partial Function
/**
* partial function
* 타입 A의 모든 값에 대해서 정의되지 않은 부분 함수 <--> 전체함수
*/
val fraction = new PartialFunction[Int, Int] {
override def isDefinedAt(x: Int): Boolean = x != 0
override def apply(v1: Int): Int = 42 / v1
}
val fraction1: PartialFunction[Int, Int] = {
case d: Int if d != 0 => 42 / d
}
val pets = List("cat", "dog", "frog")
Seq(1, 2, 42) collect pets
pets.lift(0) map ("I love my " + _) getOrElse ("")
pets.lift(42) map ("I love my " + _) getOrElse ("")
val r = ".*Scala version ([^ ]+) .*".r
val t = "Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0)."
// collect는 partial function을 인자로 받음
val i = Option(t).collectFirst {
case r(version) => version
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment