user3825558
user3825558

Reputation: 585

How to convert if statements in Scala to a case match statement block

I am in the process of learning how to code in Scala by translating from older Java code. The following code is an attempt in this learning process:

I created a class as below. Now, can the if statements in this code be replaced by case match block ? I am specifically looking to do a case match with a fall through default case that handles an exceptional case. How can I accomplish this?

class MyTest {
//ResEmail is a case class
//MultipartEnityBuilder is from the httpmime-4.4.jar

    def makeResponse(resEmail: ResEmail): HttpEntity = {
            val maker = MultipartEntityBuilder.create()
            maker.addTextBody("api_user", this.apikey)
            maker.addTextBody("api_key", this.apivalue)
            val tos = resEmail.toList
            val tonames = resEmail.toNameList
            val ccs = resEmail.ccS

            if (tos.length == 0) {
              builder.addTextBody(stringToFormattedString(ARG_TO), respEmail.fromEmail, ContentType.create("text/plain", "UTF-8"))
            }

            else if(tos.length > 0) {
              for (i <- 0 until tos.length) 
                maker.addTextBody(PARAM_TO.format(PARAM_TO, i), tos(i), ContentType.create("text/plain", "UTF-8"))
            }

            if (resEmail.fromEmail != null && !resEmail.fromEmail.isEmpty) maker.addTextBody(PARAM_FROM, resEmail.fromEmail, 
              ContentType.create("text/plain", "UTF-8"))

            if (resEmail.fromName != null && !resEmail.fromName.isEmpty) maker.addTextBody(PARAM_FROMNAME, 
              respEmail.fromName, ContentType.create("text/plain", "UTF-8"))

            if (respEmail.replyToEmail != null && !resEmail.replyToEmail.isEmpty) maker.addTextBody(PARAM_REPLYTO, 
              respEmail.replyToEmail, ContentType.create("text/plain", "UTF-8"))

            if (resEmail.subject != null && !resEmail.subject.isEmpty) maker.addTextBody(PARAM_SUBJECT, 
              resEmail.subject, ContentType.create("text/plain", "UTF-8"))

            val tmpString = new MyExpApi().jsonString()
            if (tmpString != "{}") maker.addTextBody(PARAM_MYSMTPAPI, tmpString, ContentType.create("text/plain", 
              "UTF-8"))
            maker.build()
          }


   }// end of class MyTest

Upvotes: 1

Views: 2111

Answers (1)

richj
richj

Reputation: 7529

I am specifically looking to do a case match with a fall through default case that handles an exceptional case. How can I accomplish this?

Are you looking forcase _ ?

resEmail.fromEmail match {
  case null =>
  case badEmail if badEmail.isEmpty =>
  case goodEmail =>
    maker.addTextBody(PARAM_FROM, resEmail.fromEmail, 
              ContentType.create("text/plain", "UTF-8"))
    maker.addTextBody(PARAM_FROM, resEmail.fromEmail, 
              ContentType.create("text/plain", "UTF-8"))
  case _ => throw new Exception("Case not handled.")
}

Mutator methods such as addTextBody are allowed but considered "old-school" in Scala.

Something like this would separate out the validation and construction cases:

val textBody: Option[String] = resEmail.fromEmail match {
  case null => None
  case badEmail if badEmail.isEmpty => None
  case goodEmail => Some(createContentForTextBody(goodEmail))
  case _ => throw new Exception("Case not handled.")
}

... and of course you can go further with functional style by returning the exception/result in a Try to avoid the side effect incurred with the throw (although it should be unreachable in my example because case goodEmail ought to match any case given to it).

Scala allows you to manage invalid cases more elegantly than Java, however I would argue that the best way to manage these cases is not to allow them to occur at all.

I am in the process of learning how to code in Scala by translating from older Java code.

Good luck with this. I used IntelliJ to convert an existing Java codebase to Scala. It did a pretty good job of creating valid .scala files out of .java files, but the resulting code is not good, idiomatic Scala. I learnt a lot more by rewriting one of the data structures from scratch in Scala and then load-testing it with a good profiler.

Upvotes: 2

Related Questions