Dеar Scala,Wie funktioniert eine "case" anonyme Funktion wirklich in Scala?
scala> val f1: ((Int, Int)) => Int = { case (a, b) => a + b }
f1: ((Int, Int)) => Int = <function1>
scala> val f2: (Int, Int) => Int = { case (a, b) => a + b }
f2: (Int, Int) => Int = <function2>
nicht wahr ?!
scala> f1(1, 2)
res2: Int = 3
Ok ...
scala> def takesIntInt2Int(fun: (Int, Int) => Int) = fun(100, 200)
takesIntInt2Int: (fun: (Int, Int) => Int)Int
scala> def takesTuple2Int(fun: ((Int, Int)) => Int) = fun(100, 200)
takesTuple2Int: (fun: ((Int, Int)) => Int)Int
scala> takesIntInt2Int(f2)
res4: Int = 300
scala> takesIntInt2Int(f1)
<console>:10: error: type mismatch;
found : ((Int, Int)) => Int
required: (Int, Int) => Int
takesIntInt2Int(f1)
^
scala> takesTuple2Int(f1)
res6: Int = 300
scala> takesTuple2Int(f2)
<console>:10: error: type mismatch;
found : (Int, Int) => Int
required: ((Int, Int)) => Int
takesTuple2Int(f2)
Rechts. Und nun, sieh dir das an!
scala> takesTuple2Int { case (a, b, c) => a + b + c }
<console>:9: error: constructor cannot be instantiated to expected type;
found : (T1, T2, T3)
required: (Int, Int)
takesTuple2Int { case (a, b, c) => a + b + c }
^
scala> takesIntInt2Int { case (a, b, c) => a + b + c }
<console>:9: error: constructor cannot be instantiated to expected type;
found : (T1, T2, T3)
required: (Int, Int)
takesIntInt2Int { case (a, b, c) => a + b + c }
Wie, srsly? o_O Beide führen zu required: (Int, Int)
Fehler.
Warum verwenden Sie dann case
überhaupt in solchen anonymen Funktionen?
Es wäre toll, die Lage sein, all dies zu tun, ohne 'case' Schlüsselwort. Warum der Unterschied in der Syntax für Function und PartialFunction, aus der Sicht eines normalen Entwicklers? –
@ MichałRus Um ehrlich zu sein, das störte mich immer ein wenig. Haskell und Clojure haben viel einfachere Syntaxen, um Mustervergleiche direkt auf Parameter einer Funktion auszudrücken. – wingedsubmariner