如果在Kotlin中找不到可搜索元素,我应该返回什么?

如果在Kotlin中找不到可搜索元素,我应该返回什么?,kotlin,Kotlin,我有一个方法,搜索数组中的某个元素。在Java中它是“returnnull”,但在Kotlin中我不能这样做。这样做怎么正确? 我的方法: fun find(key: Int) : DataItem { var hashValue = hashFunc(key) while (true) { if (hashArray[hashValue].key == key) { return hashArray[hashValue]

我有一个方法,搜索数组中的某个元素。在Java中它是“returnnull”,但在Kotlin中我不能这样做。这样做怎么正确? 我的方法:

fun find(key: Int) : DataItem {
    var hashValue = hashFunc(key)

    while (true) {
        if (hashArray[hashValue].key == key) {
            return hashArray[hashValue]
        } else {

        }
        ++hashValue
        hashValue %= arraySize
    }
}

您需要在函数中声明,返回的值可以是null。 在类型(T?)后添加问号


您需要在函数中声明,返回的值可以是null。 在类型(T?)后添加问号


示例中有两行无法访问:)示例中有两行无法访问:)
fun find(key: Int) : DataItem? {
var hashValue = hashFunc(key)

    while (true) {
        if (hashArray[hashValue].key == key) {
            return hashArray[hashValue]
        } else {
            return null
        }
        ++hashValue
        hashValue %= arraySize
    }
}