Is there a "kotlin" way to do something like `Scan...
# getting-started
e
Is there a "kotlin" way to do something like
Scanner(myFile).findAll(myPattern)
that returns a `Sequence<String>`(I know I can call
asSequence
on the returned
Stream
but I'm wondering if there's a specific Kotlin API for that)?
p
Since Scanner is implemented in Java, you're not going to get any better than an extension method that returns a sequence by calling
asSequence
on the stream. Unless someone has implemented a Scanner-like class for KMM, that's probably as good as you'll get
r
something like
Copy code
fun Scanner.all(matching : Pattern) = findAll(matching).asSequence()
e
Right, I guess my question is really is there a KMP function for this?
s
Scanner
is also JVM-only, isn't it? Here's the extension function that'll work on a line-sequence:
Copy code
fun Sequence<String>.findMatches(pattern: String): Sequence<String> {
    val regex = pattern.toRegex()
    return this.flatMap{line->regex.findAll(line).map{match->match.value}}
}
Here the Playground with some testdata: https://pl.kotl.in/yoF7jx5pv Now you only have to figure out how to convert your file into a
Sequence<String>
.
j
There is no Kotlin multiplatform facilities for files, because in JS browser environment you don't have access to the file system. You can work on
Sequence<String>
as others mentioned, and on JVM you can simply use Path.useLines or File.useLines like this:
Copy code
Path("yourpath").useLines { seq ->
    // do something with the sequence of lines
}
// here the file is closed automatically
e
So if the regex needed to look across lines this wouldn't work right?
j
Correct, so this might not be what you want
e
Ok thanks