kotlin - Kotlin 函数类型不匹配
问题描述
我创建了两个函数,一个是 sleepExecution 和 getCustomers 我尝试在 getCustomer 函数中使用 sleepExecution。我得到低于编译时错误
Type mismatch.
Required:
((Int) → Unit)!
Found:
KFunction2<CustomerDao, Int, Unit>
客户道.kt
package com.main.stockprice.model
import com.main.stockprice.dto.Customer
import org.springframework.stereotype.Component
import java.util.stream.Collectors
import java.util.stream.IntStream
@Component
class CustomerDao {
fun sleepExecution(i: Int){
try {
Thread.sleep(1000)
}catch (e:InterruptedException){
e.printStackTrace()
}
}
fun getCustomer():List<Customer?>?{
return IntStream.rangeClosed(1,10)
.peek(CustomerDao::sleepExecution)
.peek { i : Int -> println("processing count : $i") }
.mapToObj { i: Int -> Customer(i.toLong(),"customer$i") }
.collect(Collectors.toList())
}
}
客户.kt
package com.main.stockprice.dto
data class Customer(
val id: Long = 0,
val name: String?= null,
)
我错了或确切地指出了这一点
.peek(CustomerDao::sleepExecution)
解决方案
sleepExecution
不是静态函数,而是成员函数。您无法使用类名获取引用,而必须使用实例变量 ( this
)。在上述情况下,它应该是
IntStream.rangeClosed(1,10)
.peek(this::sleepExecution)
如果函数在伴随对象中,您可以将其用作
IntStream.rangeClosed(1,10)
.peek(CustomerDao.Companion::sleepExecution)
推荐阅读
- boto3 - Boto Stubber SQS
- performance - Spock 性能问题
- python - Yubikey 5 NFC 使用 ACR122U 在 Python 中生成 OTP
- css - 如何使用 React 中的样式在特定 div 中设置线性渐变和背景图像
- javascript - cordova/phonegap 屏幕缺口检测(适用于所有手机,不仅适用于 iPhone X)
- mysql - 如何根据 mySQL 中已存在的列自动将值插入到我创建的新列中
- python - 我无法理解这行代码的作用?
- python - Anaconda2 ImportError:没有名为 matplotlib.pylab 的模块
- python - 张量流增量嵌套 variable_scope
- android - Kotlin - RecyclerView-android.view.InflateException 项中的 BottomNavigation:二进制 XML 文件第 91 行:膨胀类错误