[英]What is java equivalent of Kotlin's Function Types?
I have code in Kotlin
and test code in Java
. 我在
Kotlin
有代码,而在Java
测试代码。 Since Kotlin
and Mockito
aren't best friends, I haven't migrated test code to Kotlin
. 由于
Kotlin
和Mockito
不是最好的朋友,因此我没有将测试代码迁移到Kotlin
。
In Kotlin
I have methods with block types. 在
Kotlin
我有使用块类型的方法。 For example: 例如:
open fun getProductInfo(resultListener: (List<Deal>)->Unit, errorListener: (Throwable)->Unit)
{
...
}
Now I want to stub this method in Java
tests. 现在,我想在
Java
测试中使用此方法。 What's the java equivalent of the types? 什么是Java类型的等效项? 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());
From the Kotlin in Action book: 从《 科特林在行动》一书中:
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.Kotlin标准库定义了一系列接口,分别对应于不同数量的函数参数:
Function0<R>
(此函数不带参数),Function1<P1, R>
(此函数带一个参数),依此类推。 Each interface defines a single invoke method, and calling it will execute the function.每个接口都定义一个调用方法,调用该接口将执行该函数。
In this case, these two functions are both Function1
instances, since they are functions that take one parameter: 在这种情况下,这两个函数都是
Function1
实例,因为它们是带有一个参数的函数:
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());
On another note, you could try mockito-kotlin and the inline version of Mockito to write your tests in Kotlin as well. 另一方面,您也可以尝试使用嘲讽-kotlin和内嵌版本的Mockito在Kotlin中编写测试。
Why not to try in Android Studio or IntelliJ, to get Java code from Kotlin: 为什么不尝试在Android Studio或IntelliJ中尝试从Kotlin获取Java代码:
This way you can continue your work with Mockito, unfortunately you will get redundant lines of code (not much) because Kotlin deal with bytecode. 这样,您可以继续使用Mockito进行工作,不幸的是,由于Kotlin处理字节码,您将获得多余的代码行(数量不多)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.