为什么我不能将Scala的Function1隐式转换为java.util.function.Function? [英] Why can't I implicit convert Scala's Function1 to java.util.function.Function?

查看:806
本文介绍了为什么我不能将Scala的Function1隐式转换为java.util.function.Function?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建Scala的Function1到java.util.function.Function的隐式转换。

I'm trying to create a implicit conversion of Scala's Function1 to java.util.function.Function.

这是我的代码:

object Java8ToScala extends App {

  implicit def javaFuncToScalaFunc[T, R](func1: Function[T, R]): function.Function[T,R] = {
    new function.Function[T, R] {
      override def apply(t: T): R = func1.apply(t)
    }
  }

  val javaFunc:function.Function[String,Int] = (s:String) => s.length

  println(javaFunc.apply("foo")) // this works

  private val strings = new util.ArrayList[String]()
  println(strings.stream().map(javaFunc).collect(Collectors.toList())) // this doesn't work

}

编译器消息很难理解:

[error] /xxx/Java8ToScala.scala:74: no type parameters for method map: (x$1: java.util.function.Function[_ >: String, _ <: R])java.util.stream.Stream[R] exist so that it can be applied to arguments (java.util.function.Function[String,Int])
[error]  --- because ---
[error] argument expression's type is not compatible with formal parameter type;
[error]  found   : java.util.function.Function[String,Int]
[error]  required: java.util.function.Function[_ >: String, _ <: ?R]
[error] Note: String <: Any, but Java-defined trait Function is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error]     .map(javaFunc).collect(Collectors.toList()))
[error]      ^
[error] /xxx/Java8ToScala.scala:74: type mismatch;
[error]  found   : java.util.function.Function[String,Int]
[error]  required: java.util.function.Function[_ >: String, _ <: R]
[error]     .map(javaFunc).collect(Collectors.toList()))
[error]          ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 7 s, completed Dec 18, 2015 10:51:15 AM


推荐答案

这只是Scala类型推断失败,虽然我不明白为什么:它似乎在寻找一个 R 扩展 AnyRef 。如果您使用这种类型,请工作,例如 val javaFunc:function.Function [String,String] =(s:String)=> s

It's just Scala type inference failing, though I don't see why: it seems to be looking for an R which extends AnyRef. It works if you use such a type, e.g. val javaFunc: function.Function[String,String] = (s:String) => s.

然而,它没有获得任何上限:使用 map [Int] 也明确工作

However, it isn't getting an upper bound anywhere: using map[Int] explicitly works as well.

这篇关于为什么我不能将Scala的Function1隐式转换为java.util.function.Function?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆