【发布时间】:2016-02-03 16:49:21
【问题描述】:
从 Java 8 开始我可以通过
xyz.foreach(e -> System.out.println(e));
我可以做到以下几点
xyz.foreach(System.out::println)
我看过this thread关于方法引用的工作原理,但问题如下:
错误:(16, 63) 对重载定义的模糊引用,
对象 IanesJsonHelper 中的 toJson 方法(来源:IanesServer)String
对象IanesJsonHelper中的toJson方法(成功:Boolean)String
匹配预期类型 Function[?,String]
val json = IanesJsonHelper.toJson(array,IanesJsonHelper.toJson _) ^
我确实有 3 个名为“toJSON”的函数
def toJson(id: Int): String
和
def toJson(success: Boolean): String
和
def toJson(source: IanesServer): String
最后一个是正确的。
我在上面的错误信息中调用的函数是:
def toJson[T](source: Array[T], toJson: Function[T, String]): String
这是相关代码:
val array = new Array[IanesServer](1)
array(0) = new IanesServer(1, "http://localhost:4567/", "Test")
val json = IanesJsonHelper.toJson(array,IanesJsonHelper.toJson)
我不明白我的错误是什么:
- 数组的类型是 IanesServer
- 调用方法中的T应该是IanesServer(Array[IanesServer] -> Array[T]
- 由于 2. 函数中的 T 必须与数组中的 T 相同,因此必须是 Function[IanesServer,String] -> Function[T,String]
有人能指出错误吗?目前我强烈反对该函数是 [?,String]。有什么想法吗?
回答: 感谢您的快速回答,这是我选择的:
IanesJsonHelper.toJson[IanesServer](array,IanesJsonHelper.toJson)
【问题讨论】:
标签: java scala generics java-8