1

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
2
  • 2
    So what's the problem? what did you try so far? Provide the code of case class. Commented Apr 26, 2015 at 22:34
  • I am writing my case statements now. Commented Apr 26, 2015 at 22:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes the case _ construct.
Also worth noting that Option(null) returns null, and then you can use collect instead of match and just have no cases for the None cases.
I meant Option(null) returns None
You wrote one of the data structures from scratch. That is interesting. Which one do you recommend?
I chose the Revised R*-Tree described in a paper written by Norbert Beckmann and Bernhard Seeger. It's one of the articles published in ISBN 978-1-60558-551-2. The paper is available from the ACM Digital Library. I chose it because I'm interested in spatial indexes and had already implemented it once, in Java. I would recommend choosing a data structure (or any other problem) that interests you and is about the right level of difficulty for your progress with Scala and the time that you have to spend on it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.