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.
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)
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("")