首页 > 解决方案 > 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)

标签: kotlin

解决方案


sleepExecution不是静态函数,而是成员函数。您无法使用类名获取引用,而必须使用实例变量 ( this)。在上述情况下,它应该是

IntStream.rangeClosed(1,10)
        .peek(this::sleepExecution)

如果函数在伴随对象中,您可以将其用作

IntStream.rangeClosed(1,10)
        .peek(CustomerDao.Companion::sleepExecution)

推荐阅读