Comment le code vous un bloc de code correspondant à motif en scala?
-
25-09-2019 - |
Question
Comment le code vous une fonction qui prend dans un bloc de code comme un paramètre qui contient des déclarations de cas? Par exemple, dans mon bloc de code, je ne veux pas faire un match ou un cas de défaut explicitement. Je cherche quelque chose comme ça
myApi {
case Whatever() => // code for case 1
case SomethingElse() => // code for case 2
}
Et à l'intérieur de mon MyApi (), il va exécuter effectivement le bloc de code et faire les matchs.
La solution
Vous devez utiliser un PartialFunction
pour cela.
scala> def patternMatchWithPartialFunction(x: Any)(f: PartialFunction[Any, Unit]) = f(x)
patternMatchWithPartialFunction: (x: Any)(f: PartialFunction[Any,Unit])Unit
scala> patternMatchWithPartialFunction("hello") {
| case s: String => println("Found a string with value: " + s)
| case _ => println("Found something else")
| }
Found a string with value: hello
scala> patternMatchWithPartialFunction(42) {
| case s: String => println("Found a string with value: " + s)
| case _ => println("Found something else")
| }
Found something else
Autres conseils
Cela devrait suffire à expliquer: Un tour de Scala: Recherche de modèles
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow