Reputation: 63201
I am trying to read an input stream in chunks:
import scala.io.Source
// val in = Source.stdin.mkString("")
val in = Source.fromFile("/shared/american.txt").getLines.mkString("")
var ptr = 0
val out = Stream.continually {
val ix = math.min(ptr+80,in.length)
val ret = in.substring(ptr, ix)
ptr = ix
ret
}
out: scala.collection.immutable.Stream[String] = Stream(Unmentionable has an enthusiastic 35% of the popular vote. I discount the other 10% or s, ?)
But what is the syntax for take
in chunks? I tried:
val chunks = out.takeWhile( ptr < in.length)
<console>:13: error: type mismatch;
found : Boolean
required: String => Boolean
val ret = out.takeWhile( ptr < in.length)
Upvotes: 0
Views: 83
Reputation: 51271
Reading a file in 80 character chunks? How 'bout this?
val in = io.Source.fromFile("file.txt").mkString.grouped(80)
while (in.hasNext) {
// in.next is your chunk
}
Upvotes: 1
Reputation: 18187
What are you trying to accomplish? If you are just trying to break a string (file) into chunks you could use the .grouped()
or .groupBy()
functions.
As for your current error, the compiler tells you what you need to do. You're giving a Boolean:
val chunks = out.takeWhile(ptr < in.length) // ptr < in.length evaluates to a boolean
but you need to give a function that takes a String and returns a Boolean:
val chunks = out.takeWhile(s => ptr < s.length) // Something like this
Upvotes: 0