# Clean phone number

Program that cleans up user-entered phone numbers so that they can be sent SMS messages. The rules are as follows:

• If the phone number is less than 10 digits assume that it is bad
number
• If the phone number is 10 digits assume that it is good
• If the phone number is 11 digits and the first number is 1, trim the 1 and use the last 10 digits
• If the phone number is 11 digits and the first number is not 1, then it is a bad number
• If the phone number is more than 11 digits assume that it is a bad number

Here is the gist with correspondent specs.

The solution that I've came up with:

class PhoneNumber(phone: String) {

def number = if(valid_phone) clean_phone else "0000000000"

def areaCode = clean_phone.take(3)

override def toString = s"($areaCode)${clean_phone.substring(3,6)}-\${clean_phone.takeRight(4)}"

private def valid_phone = clean_phone.length == 10

private val clean_phone = {
val clean_number = phone.filter(_.isDigit)
if (clean_number.length == 11 && clean_number(0) == '1') clean_number.tail else clean_number
}

}


Here is a couple of questions that I have:

• Should I always use val instead of def when the return value is not going to change and I can avoid multiple calculation of the same thing?
• Why am I getting an exception when I try to change def valid_phone to a val? Its about Java Null Pointer Exception.

The reason why changing valid_phone to a val gives a NullPointerException is a little, but important detail that new Scala developers sometimes forget. In Scala, a class definition is also the primary constructor for instances of that class. In the code above, if you change valid_phone to a val, then at the time the line is evaluated, the value of clean_phone has not been initialized and is null. If you want to make valid_phone a val, then you have to put it after clean_phone.