javadba javadba - 18 days ago 7
Scala Question

TakeWhile results in type mismatch

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)

Answer

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