Kotlin load a collection of a class from a file?

In C++ I can load a collection of a class from a file using a friend operator>> overload:

friend std::istream& operator>>(std::istream& is_a, College& college_a) {
    return is_a >> college_a.id_,
        is_a.get(),
        std::getline(is_a,college_a.name_);
}

std::set<College> colleges {};
std::copy(std::istream_iterator<College> {std::cin},
    std::istream_iterator<College> {},
    std::inserter(colleges, colleges.begin())); 

from a file like this:

0707 Rowan Technical College
0980 University of Saskatchewan
1058 Belmont University
1072 Belmont Technical College

How would this be done with Kotlin?

1 answer

  • answered 2019-07-11 15:23 Rene

    There are many ways to parse a file and split the lines in Kotlin / Java. The next example uses a Regex to split the line into an id and the name for the college:

    data class College(val id: String, val name: String)
    
    val colleges = File("input.txt").useLines { lines ->
        val regex = Regex("(\\d+) (.+)")
        lines.mapNotNull { line ->
            regex.matchEntire(line)?.let {
                College(it.groupValues[1], it.groupValues[2])
            }
        }.toList()
    }
    

    If you need to read from the standard input, then replace the third line with:

    val colleges = InputStreamReader(System.`in`).useLines { lines ->