Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I was wondering if someone had any suggestions on how to make this code snippet more elegant.

val names = Buffer[String]()
var name: String = null
do {
  val input = readLine("Name: ")
  if (names contains input) {
    println("Name was taken already. Try again.")
  } else {
    name = input
} while (name == null)

locked by Jamal Jan 29 at 18:37

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

1 Answer 1

up vote 16 down vote accepted

Currently the code is not very elegant (or at least not very functional) because it contains mutable variables and a while loop. So let's get rid of those.

In functional languages we can usually achieve the most elegant solutions if we're working with sequences (e.g. lists or streams) as input. If we had the input as a sequence of strings in this case, we could simply write this to get the first name not in the list of names:

inputNames.find( !names.contains(_) )

So how do we get the input into a stream? We can use Stream.continually to create an infinite, lazy stream of input:

def askForName() = readLine("Name: ")

def askForNameAgain() = {
    println("Name was taken already. Try again.")

def inputNames = Stream.cons( askForName(), Stream.continually(askForNameAgain()))

val name = inputNames.find( !names.contains(_) )

Note that this way name will be a Option[String]. If the user closes the input stream before entering a valid name, name will be None. Otherwise it will be Some(theName). If you want to ignore the possibility that the user may close the stream, you can simply add a call to Option.get.

Excellent, thank you sepp2k. Very nice solution. So much to learn from scala.. :) – Dale Wijnand Sep 3 '11 at 7:23
Excellent answer. I was vaguely feeling a lazy stream was the answer, but I was unable to express it, even less in the elegant way you did. – PhiLho Sep 5 '11 at 9:50

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