Mic*_*Rus 24 scala pattern-matching
Dast 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>
Run Code Online (Sandbox Code Playgroud)
呵呵?
scala> f1(1, 2)
res2: Int = 3
Run Code Online (Sandbox Code Playgroud)
好...
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)
Run Code Online (Sandbox Code Playgroud)
对.现在,看看这个!
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 }
Run Code Online (Sandbox Code Playgroud)
像,srsly?o_O都导致required: (Int, Int)错误.
为什么然后case在这样的匿名函数中使用呢?
win*_*ner 17
请参阅Scala参考资料的8.5节(http://www.scala-lang.org/files/archive/nightly/pdfs/ScalaReference.pdf).表达式{ case (a, b) => a + b }根据预期类型进行不同的解释.在你的定义中f1创建了一个PartialFunction[(Int, Int), Int]被转换为a Function1[(Int, Int), Int],即((Int, Int)) => Int在f2它的定义中创建了一个Function2[Int, Int, Int],即(Int, Int) => Int.
这两种解释与您在匿名函数中通常使用案例的两种情况有关.
一个用于编写接受元组并在其组件上工作的匿名函数,就像您一样f1.一个例子是你传递给a foreach或map方法的函数Map,例如Map(1 -> 2, 3 -> 4) map { case (k, v) => k + v }.
第二个是编写一个匿名函数,它match在其唯一参数上执行.你f2这样做,但没有任何有用的方式.一个例子是传递给的匿名函数collect,例如List(1, -2, 3) collect { case x if x > 0 => -x }.
请注意,两者可以组合,也就是f1可以执行复杂匹配的功能.例如,Map(1 -> 2, 3 -> 4) collect { case (k, v) if k < 2 => v }.
编辑:res2因为元组而起作用.如果应用程序没有键入check,编译器将尝试在失败之前将args包装在元组中.
但这仅适用于应用程序; 你发现它并不是一般的转换.它不会尝试将值升级Function2[A, B, C]为Function1[(A, B), C].