Home > other >  How to call lines from a mutable list in kotlin
How to call lines from a mutable list in kotlin

Time:11-21

I am college student, trying to figure out a school project and I seem to be hitting some roadblocks. I have a file with a list of items that fit into different classed I have made. I know how to read the file in total:

class Inventory(var fileName: String) {
    override fun toString(): String {
        return """
            $fileName
        """.trimIndent()
    }
    init {
        val myList = mutableListOf<String>()
        File(fileName).useLines { lines -> myList.addAll(lines) }
        myList.forEachIndexed { i, line -> println("${i}: "   line) }

        if (lines[1] = --column1--){
           put line in a class object
        }
    }
}

I'm trying to call specific lines, in the text file in question, using Lines, basically saying if (line[1] = "the first column") do 'this', but lines isn't allowing me to do it. How would I make Lines work or is there an easier way to call specific line and then column?

The goal is to get a specific line in the text and to put it into a specific class object. I know how to put it in a class object, I'm just trying to call the specific line.

I appreciate the help!

CodePudding user response:

I hope that I understood the question correctly... you can simplify your code as follow:

class Inventory(private val fileName: String) {

    private val lines: List<String> = File(fileName)
        .readLines()
        .filter { it ==  "the first column" }
        .toList()

    override fun toString() = fileName
}

Note that this code is really inefficient as you read the entire file only to get the 1st line, the idea was just to give you an example of how you can operate it.

Moreover, you don't need to use string format just to return the file name so I simplified a bit your toString method

last but not least, keep in mind that lines was a variable that was defined inside an anonymous function inside the constructor of the class and therefore is not available once the function is finished. to solve this I defined the class member lines and initiated it when the class is created.

Last but not least, I switched from mutable list to immutable list as it's safer and in here you actually don't need to mutate the list :)

  • Related