什么是Kotlin函数类型的Java等效项? [英] What is java equivalent of Kotlin's Function Types?
问题描述
我在Kotlin
中有代码,在Java
中有测试代码.由于Kotlin
和Mockito
不是最好的朋友,因此我没有将测试代码迁移到Kotlin
.
I have code in Kotlin
and test code in Java
. Since Kotlin
and Mockito
aren't best friends, I haven't migrated test code to Kotlin
.
在Kotlin
中,我具有块类型的方法.例如:
In Kotlin
I have methods with block types. For example:
open fun getProductInfo(resultListener: (List<Deal>)->Unit, errorListener: (Throwable)->Unit)
{
...
}
现在,我想在Java
测试中将此方法存根.什么是Java类型的等效项?换句话说,我应该用什么代替下面的??? s:
Now I want to stub this method in Java
tests. What's the java equivalent of the types? In other words, what should I write in place of ???s below:
doAnswer(invocation -> {
??? resultListener = (???) invocation.getArguments()[0];
// call back resultListener
return null;
}).when(api).getProductInfo(any(), any());
推荐答案
来自 行动中的科特林 本书:
Kotlin标准库定义了一系列接口,分别对应于不同数量的函数参数:
Function0<R>
(此函数不带参数),Function1<P1, R>
(此函数带一个参数),依此类推.每个接口都定义一个调用方法,调用该接口将执行该功能.
The Kotlin standard library defines a series of interfaces, corresponding to different numbers of function arguments:
Function0<R>
(this function takes no arguments),Function1<P1, R>
(this function takes one argument), and so on. Each interface defines a single invoke method, and calling it will execute the function.
在这种情况下,这两个函数都是Function1
实例,因为它们是带有一个参数的函数:
In this case, these two functions are both Function1
instances, since they are functions that take one parameter:
Mockito.doAnswer(invocation -> {
Function1<List<Deal>, Unit> resultListener =
(Function1<List<Deal>, Unit>) invocation.getArguments()[0];
Function1<Throwable, Unit> errorListener =
(Function1<Throwable, Unit>) invocation.getArguments()[1];
resultListener.invoke(new ArrayList<>());
return null;
}).when(api).getProductInfo(any(), any());
另一方面,您可以尝试 mockito-kotlin 和Mockito的内联版本,也可以在Kotlin中编写测试.
On another note, you could try mockito-kotlin and the inline version of Mockito to write your tests in Kotlin as well.
这篇关于什么是Kotlin函数类型的Java等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!