Search code examples
kotlinkotlin-android-extensionskotlin-extensionrx-kotlinkotlin-interop

Required <Object> and found <Object>?


class TaskRepo(taskData: TaskData) {

companion object {
    private val repoByTask: LRUMap<String, OrderFormRepo> = LRUMap(2, 10);

     fun getInstance(taskData: TaskData): OrderFormRepo {
        if (notFoundObject(taskData.taskId)) {
            repoByTask[taskData.taskId] = OrderFormRepo(taskData);
        }
        return repoByTask[taskData.taskId];//PROBLEM HERE
    }

    private fun notFoundObject(taskId: String): Boolean {
        if (repoByTask.containsKey(taskId) && repoByTask[taskId] != null) {
            return false
        }
        return true
    }
}

}

in getInstance method of companion object I am getting compile time error: Required TaskRepo and found TaskRepo?


Solution

  • LRUMap implements the Map interface, the get method of which in Kotlin returns a V?, as it returns null when no element is present for the given key.

    As you've already done the checking beforehand in this case, you can be reasonably sure (assuming no other threads are modifying the map at the same time) that this value won't be null, and force a conversion to the non-nullable type with the !! operator:

    return repoByTask[taskData.taskId]!!
    

    For other ways to handle a missing key when reading from a Map, see the getOrDefault and getOrElse methods.