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?
LRUMap
implements theMap
interface, theget
method of which in Kotlin returns aV?
, as it returnsnull
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:For other ways to handle a missing key when reading from a
Map
, see thegetOrDefault
andgetOrElse
methods.