Home > Back-end >  type mismatch when trying to read List from internal Storage
type mismatch when trying to read List from internal Storage

Time:09-24

I am new to Kotlin so please excuse this question, as it is probably pretty stupid...

So I followed the tutorial by Philipp Lackner to create a Todo-List as an android app if any of you know that. Now I tried to add a read and write functionality to this app by saving into a simple .txt-file for now. For that I tried to follow this tutorial as much as possible, but now I am running into Problems when writing code to load the Todo-Items from a file.

I wrote this function to load Todo-Items from the .txt-file:

private suspend fun loadTodoItemsFromInternalStorage(): List<Todo> {
    return withContext(Dispatchers.IO) {
        val todoItemList: MutableList<Todo> = mutableListOf<Todo>()
        var isEven = true
        val files = filesDir.listFiles()
        files?.filter { it.canRead() && it.isFile && it.name.endsWith(".txt") }?.map {
            val lines = it.bufferedReader().readLines()
            for (i in lines.indices) {
                isEven = if(isEven) {
                    todoItemList.add(Todo(lines[i], lines[i 1].toBoolean()))
                    !isEven
                } else {
                    !isEven
                }
            }
            todoItemList
        } ?: mutableListOf<Todo>()
    }
}

Why do I get that type mismatch? I even initialize the list I want to return as a MutableList of type Todo, but I guess the type inference of Kotlin turns it into a MutableList of type Any?

So how do I fix this? And if you want to you could tell me better ways to do what I did (e.g. saving Todo-items (which consist of title and a boolean whether they are checked or not) to a file)

My plan to keep this as simple as possible as this is my first Kotlin project was to just use 2 lines for a Todo-item, where the first line is the title and the second line is the status whether it has been checked or not. I hope that makes my code easier to understand.

Thank you so much for your help in advance! I appreciate it a lot, as I have been struggling with coding in the past and really want to improve my coding skills.

CodePudding user response:

If you cast your return statement, the code should work. Taking your code as a basis:

private suspend fun loadTodoItemsFromInternalStorage(): List<Todo> {
    return withContext(Dispatchers.IO) {
        ...
        } ?: mutableListOf<Todo>()
    } as MutableList<Todo>
}

Some additional suggestions:

  • when dealing with file handling in general: error handling, check for correct format, empty entries, ...
  • the check for isEven/isOdd is obsolete and the code can be shortened to great extent when you use the step-option within the for-loop
for (i in lines.indices step 2) {
    todoItemList.add(Todo(lines[i], lines[i 1].toBoolean()))
}
  • Related