Reputation: 3066
I wrote a socket program in scala and I want to know when I get response from server. Here is the code:
class Client(val id:Int) extends Runnable{
override def run(): Unit = {
val s = new Socket
val address = new InetSocketAddress("localhost",9977)
s.connect( address )
val lines = Source.fromInputStream(s.getInputStream).getLines()
lines foreach println // print result
println("%d connected" format id)
// lines foreach println // print result after
s.close
}
}
However if I don't print the result( lines foreach println
) out or print it later, println("%d connected" format id)
is executed instantly.
The server side takes a long time to give the response. It shouldn't be instant. I wonder why this happens?
Is it value 'lines' be evaluated lazily?
Can I evaluate 'lines' before executing the following code?
Upvotes: 1
Views: 1129
Reputation: 16412
You didn't include import
statements, so I'm guessing you are using scala.io.Source
. In that case scala.io.Source.fromInputStream(...).getLines()
returns an Iterator
and iterators are lazy. Here is the signature:
def getLines(): collection.Iterator[String]
This is actually nice, because you might not want to get all lines if you are receiving lots of data. If you want to force it to materialize just convert iterator to a collection like this for example:
lines.toList
Upvotes: 1