7
\$\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
        }
      }
\$\endgroup\$
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"))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.