Search code examples
scalaformattingmessageformat

Scala: Better way for String Formatting to PhoneNumber and using Java's MessageFormat


I'm looking for a better way to better implement the following:

I have imported import java.text.MessageFormat to set the format I would like.

  1. val szphoneFrmt holds the format I would like.
  2. val szInitialString is set to the value I pulled from the database.
  3. val szWorkString breaks up the string via substring.
  4. val szWorkPhone is the final string with the formatted string.

Now the problem that I am seeing is that sometimes the value in the database is null and so szInitialString is null, so I have put in a check to prevent an out of bounds exception. Now this code is working and I am able to format the string properly, but I don't think this is a good solution.

Does anyone have any suggestions with tidying this code up? I would be completely okay with dropping the use of Java's MessageFormat, but I have not seen any other reasonable solutions.

  val szphoneFrmt = new MessageFormat("1 {0}{1}-{2}")  
  val szInitialString = applicant.ApplicantContact.Phone1.toString
  val szWorkString = { 
      if (szInitialString != null) {
          Array(szInitialString.substring(0,3), 
                szInitialString.substring(3,6), 
                szInitialString.substring(6))
      } else { null } 
  }

  val szWorkPhone = phoneFrmt.format(szWorkString)

Solution

  • Since we don't like nulls I wrapped your possibly-null value into an Option. If the option have a value I create the array from it and then pass it into the formatter. If it didn't have a value I give it the value "".

    val szPhoneFrmt = new MessageFormat("1 {0}{1}-{2}")  
    val szInitialString = Option(applicant.ApplicantContact.Phone1.toString)
    val szWorkString = szInitialString
        .map { s => Array(s.substring(0,3), s.substring(3,6), s.substring(6)) }
        .map(szPhoneFrmt.format)
        .getOrElse("")