'Type mismatch: inferred type is Unit but Resource<TypeVariable(T)> was expected

Creating a simple notes app to practice MVVM architecture, where we upload to note to Firebase Firestore.

Resource.kt

sealed class Resource<T>(val data: T? = null, val message: String? = null) {
    class Success<T>(data: T) : Resource<T>(data)
    class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
    class Loading<T>(data: T? = null) : Resource<T>(data)
}

RepositoryUtil.kt

inline fun <T> safeCall(action: () -> Resource<T>): Resource<T> {
    return try {
        action()
    } catch (e: Exception) {
        Resource.Error(e.message ?: "Something went wrong!")
    }
}

MainRepository.kt

interface MainRepository {
    suspend fun addNote(text: String): Resource<Note>
    suspend fun getNotes(): Resource<List<Note>>
}

DefaultMainRepository.kt

@ActivityScoped
class DefaultMainRepository : MainRepository {

    private val firestore = FirebaseFirestore.getInstance()
    private val notes = firestore.collection("notes")

    override suspend fun addNote(text: String) = withContext(Dispatchers.IO) {
        safeCall {}
    }
}

Getting this error once I add safeCall{} under addNote() in DefaultMainRepository.kt.

Type mismatch: inferred type is Unit but Resource<TypeVariable(T)> was expected


Solution 1:[1]

You aren't providing a lambda to safeCall that returns a resource. The empty safeCall {} is really safeCall( { Unit } ), but you defined safeCall to accept a action: () -> Resource<T>.

Try temporarily replacing safeCall {} with safeCall { Resource.Error("Test") } and see if that resolves the compiler error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 b_camphart