# How can I make this do-while loop more elegant scala

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 {
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.

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: ")

println("Name was taken already. Try again.")

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.