https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

eygraber

11/16/2021, 4:00 AM
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

Paul Griffith

11/16/2021, 6:25 AM
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

Rein T

11/16/2021, 7:14 AM
something like
Copy code
fun Scanner.all(matching : Pattern) = findAll(matching).asSequence()
e

eygraber

11/16/2021, 8:26 AM
Right, I guess my question is really is there a KMP function for this?
s

Stephan Schroeder

11/16/2021, 10:16 AM
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

Joffrey

11/16/2021, 1:22 PM
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

eygraber

11/16/2021, 4:33 PM
So if the regex needed to look across lines this wouldn't work right?
j

Joffrey

11/16/2021, 4:36 PM
Correct, so this might not be what you want
e

eygraber

11/16/2021, 4:40 PM
Ok thanks
3 Views