javadba javadba - 1 year ago 85
Scala Question

TakeWhile results in type mismatch

I am trying to read an input stream in chunks:


// 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

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
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download