如何在Scala中调用Function1[\ux,String]?
我回答了一个关于函数映射的问题,其中导致了如何在Scala中调用Function1[\ux,String]?,scala,types,Scala,Types,我回答了一个关于函数映射的问题,其中导致了Function1[\uu,String],我认为就键入问题而言,它是正确的,但可能没有用,因为我不知道如何调用这样的函数: scala> def f(x: Int) = x.toString f: (x: Int)java.lang.String scala> f(8) res0: java.lang.String = 8 scala> val g: Function1[_, String] = f _ g: Function1[
Function1[\uu,String]
,我认为就键入问题而言,它是正确的,但可能没有用,因为我不知道如何调用这样的函数:
scala> def f(x: Int) = x.toString
f: (x: Int)java.lang.String
scala> f(8)
res0: java.lang.String = 8
scala> val g: Function1[_, String] = f _
g: Function1[_, String] = <function1>
scala> g(8)
<console>:8: error: type mismatch;
found : Int(8)
required: _$1 where type _$1
g(8)
^
scala> val h: Function1[Int, String] = g
<console>:7: error: type mismatch;
found : (_$1) => String where type _$1
required: (Int) => String
val h: Function1[Int, String] = g
scala>def(x:Int)=x.toString
f:(x:Int)java.lang.String
scala>f(8)
res0:java.lang.String=8
scala>val g:Function1[\ux,String]=f_
g:Function1[_,String]=
scala>g(8)
:8:错误:类型不匹配;
发现:Int(8)
必填项:$1,其中类型$1
g(8)
^
scala>valh:Function1[Int,String]=g
:7:错误:类型不匹配;
找到:($1)=>字符串,其中类型为$1
必需:(Int)=>字符串
val h:Function1[Int,String]=g
有没有办法使用
g
?我想说,这就像你把String
类型的对象强制转换为any
,如果你想使用String
中定义的方法,你必须把它强制转换回String
您将函数强制转换为接受存在类型的参数的函数(这是类型上下文中\uu
的意思),因此不能将其用作接受Int
的函数。要将其用作接受Int
的函数,必须将其回退
在与集合或其他泛型类进行模式匹配时,也存在相同的问题:
def firstLength(collection: Any): Int ={
collection match {
// this is how you would have liked to write it
// case list: List[String] => list.head.length
// case map: Map[String, String] => map.values.head.length
// but this is how you have to write it because of type erasure
case list: List[_] => list.asInstanceOf[List[String]].head.length
case map: Map[_, _] => map.asInstanceOf[Map[String, String]].values.head.length
}
}
类型信息不存在,因此您无法在List[String]
上进行匹配,而是必须在存在类型List[\u]
上进行匹配(您这样说可能有误,我认为它不是存在的泛型类型),然后强制转换。这或多或少正是你的问题所在,你要找的类型已经被删除了,而且没有办法把它取回(除非你可以对ClassManifest
使用相同的技巧,在类似上面的情况下可以用来绕过类型删除[但实际上不是上面的情况,因为它有点草率])
它将起作用,因为所有函数都擦除为相同的内容:Function1[AnyRef,AnyRef]
。当您将其指定为Any
时,传递AnyVal
将在调用时自动将其装箱(并且将在方法中自动取消装箱)
但是,您必须传递正确的参数类型。否则
scala> g.asInstanceOf[Any => String](true)
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Integer
g、 asInstanceOf[Function1[Int,String]](8)有效,但我认为这不是一个好答案。。。假设中的语法(不是您的答案,而是实际的原始问题)确实有效,那么调用映射中函数的代码是什么样子的?执行映射查找后,他打算如何将正确的类型发送到正确的函数?不过,您可以对集合调用
collect
,以安全地修复该类型。不过,它会默默地过滤掉任何不匹配的元素——除非您放入一个引发异常的默认子句。
scala> g.asInstanceOf[Any => String](true)
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Integer