Scala通用功能值(匿名函数) – 缺少参数类型(错误)
发布时间:2020-12-16 19:00:55 所属栏目:安全 来源:网络整理
导读:我是 Scala的新人( Scala代码转换器2.7.7.final),我真的不明白为什么它要求调用者在使用高阶函数时提供参数类型. 在下面的示例中,我有一个独立的对象(Util)具有一个功能.但是在主程序段中,调用者必须将参数类型传递给匿名函数. 为什么Scala不会从Array类型(
我是
Scala的新人(
Scala代码转换器2.7.7.final),我真的不明白为什么它要求调用者在使用高阶函数时提供参数类型.
在下面的示例中,我有一个独立的对象(Util)具有一个功能.但是在主程序段中,调用者必须将参数类型传递给匿名函数. 为什么Scala不会从Array类型(即String)中推断出函数的类型?有什么办法吗? object Util { // Just for fun! Suppose that the arrayOne and arrayTwo are all the same length. // will swap the elements from arrayOne to ArrayTwo. def swap[T](arrayOne:Array[T],arrayTwo:Array[T],f:(T,T) =>(T,T)) { for(i <- 0 until (arrayOne.length min arrayTwo.length)){ val (left,right) = f(arrayOne(i),arrayTwo(i)) arrayOne(i) = left arrayTwo(i) = right } } } object Main extends Application { val arrayOne = Array("A","B","C") val arrayTwo = Array("D","E","F") //If not specified the type String,the compiler throws "Missing Parameter Type" error Util swap(arrayOne,arrayTwo,(elem1:String,elem2:String)=>(elem2,elem1)) } 解决方法
它不推断T的类型,因为在这一点上唯一必须去的是arrayOne和arrayTwo.但是,Scala不使用一个参数的类型来推断另一个参数的类型,可能是因为它会导致方法重载的问题.但是,如果你咖喱它,它是有效的:
Object Util { // Just for fun! Suppose that the arrayOne and arrayTwo are all the same length. // will swap the elements from arrayOne to ArrayTwo. def swap[T](arrayOne:Array[T],arrayTwo:Array[T])(f:(T,T)) : Unit = { var i = 0 var tuple :Tuple2[T,T] = null while(i < arrayOne.length && i < arrayTwo.length){ tuple =f(arrayOne(i),arrayTwo(i)) arrayOne(i) = tuple._1 arrayTwo(i) = tuple._2 i+=1 } } } object Main extends Application { // val works fine below -- the object is mutable val arrayOne = Array("A","F") (Util swap(arrayOne,arrayTwo))((elem1,elem2)=>(elem2,elem1)) // The weird parenthesis is caused by mixing operator notation and currying // One could also write it like this: // Util.swap(arrayOne,arrayTwo)((elem1,elem1)) } 如果咖喱它工作正常,原因是curried方法实际上是接收第一个参数列表并返回一个需要其他(或其他)参数列表的函数的方法.因此,可以在第一个参数列表中确定重载,因此第二个参数列表可以利用推断的类型. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |