8
\$\begingroup\$

I have a small TCP service running on port 4444 which, given a word, will look up synonyms in a dictionary. Below is my Scala code for connecting to the socket, sending the lookup command and parsing the response. If the word exists, then the last line of the response from the service will contain a string with 200 as the status code, otherwise it will return 404.

How can I make this code easier to read and more idiomatic?

private def lookupWord(word: String): Option[String] = {
 val socket = new Socket(InetAddress.getByName("localhost"), 4444)
 val out = new PrintStream(socket.getOutputStream)
 val reader = new BufferedReader(new InputStreamReader(socket.getInputStream, "utf8"))
 out.println("LOOKUP " + word)
 out.flush()
 var curr = reader.readLine()
 var response = ""
 while(!curr.contains("200") && !curr.contains("404")) {
 response += curr + "\n"
 curr = reader.readLine()
 }
 socket.close()
 curr match {
 case code if code.contains("200") => {
 Some(response)
 }
 case _ => None
 }
 }
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Sep 17, 2014 at 2:01
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

What about something like this?

val socket = new Socket(InetAddress.getByName("localhost"), 4444)
val out = new PrintStream(socket.getOutputStream)
val bs = BufferedSource(new InputStreamReader(socket.getInputStream, "utf8"))
out.println("LOOKUP " + word)
out.flush()
val output = bs.getLines.find(_.contains("200"))
socket.close()
output

FWIW in the general case you could replace that sort of match construct you're using with something like this:

Option(curr).filter(_.contains("200"))
answered Oct 4, 2014 at 18:36
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.