1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

scala: vol1. PartitalFunction(ぱふ) とは?

Posted at

scala: vol1. PartitalFunction(ぱふ) とは?

akka-grpc で、PartitalFunctionが登場し今まで使ったことがなかったので調査したことをまとめました。

概要

PartialFunctionは、全ての引数の入力値に対して、特定の値の時にしか返さない関数です。

これはどういうことか?

具体的に実行してみましょう!

実践

scala> val pf1: PartialFunction[String, Int] = { case "one" => 1 }
pf1: PartialFunction[String,Int] = <function1>

scala> pf1("one")
res8: Int = 1

scala> pf1("two")
scala.MatchError: two (of class java.lang.String)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:259)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:257)
  at $anonfun$1.applyOrElse(<console>:11)
  at $anonfun$1.applyOrElse(<console>:11)
  at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
  ... 28 elided

普通の関数と同じように呼び出します。
上記の関数では、"one" 以外の値を渡すとMatchError になります。

また以下のようにPartialFUnctionを合成して定義することも可能です。

scala> val pf1: PartialFunction[String, Int] = { case "one" => 1 }
pf1: PartialFunction[String,Int] = <function1>

scala> val pf2: PartialFunction[String, Int] = { case "two" => 2 }
pf2: PartialFunction[String,Int] = <function1>

scala> val pf: PartialFunction[String, Int] = pf1 orElse pf2
pf: PartialFunction[String,Int] = <function1>

scala> pf("one")
res3: Int = 1

scala> pf("two")
res4: Int = 2

scala> pf("three")
scala.MatchError: three (of class java.lang.String)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:259)
  at scala.PartialFunction$$anon$1.apply(PartialFunction.scala:257)
  at $anonfun$1.applyOrElse(<console>:11)
  at $anonfun$1.applyOrElse(<console>:11)
  at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
  at $anonfun$1.applyOrElse(<console>:11)
  at $anonfun$1.applyOrElse(<console>:11)
  at scala.PartialFunction$OrElse.apply(PartialFunction.scala:172)
  ... 28 elided

pf1の呼び出しの時同様に、pf() で許可していない値を渡した場合MatchErrorになります。

許可している値かどうかを調べるためには、isDefineAtメソッドを使うことにより確認できます。

scala> pf.isDefinedAt("one")
res6: Boolean = true

scala> pf.isDefinedAt("three")
res7: Boolean = false

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?