{"id":528,"date":"2011-09-29T08:10:00","date_gmt":"2011-09-29T08:10:00","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/2012\/10\/scala-tutorial-conditional-execution-with-if-else-blocks-and-matching.html"},"modified":"2012-10-21T20:10:20","modified_gmt":"2012-10-21T20:10:20","slug":"scala-tutorial-conditional-execution","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html","title":{"rendered":"Scala Tutorial &#8211; conditional execution with if-else blocks and matching"},"content":{"rendered":"<div dir=\"ltr\" style=\"text-align: left\">\n<h2>             Preface<\/h2>\n<p>This is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other resources on <a href=\"http:\/\/icl-f11.utcompling.com\/links\">the links page of the Computational Linguistics course<\/a> I\u2019m creating these for. Additionally you can find this and other tutorial series on the JCG <a href=\"http:\/\/www.javacodegeeks.com\/p\/java-tutorials.html\">Java Tutorials<\/a> page.<\/p>\n<h2>             Conditionals<\/h2>\n<p>Variables come and variables go, and they take on different values depending on the input. We typically need to enact different behaviors conditioned on those values. For example, let\u2019s simulate a bar tender in Austin who must make sure that he doesn\u2019t give alcohol to individuals under 21 years of age.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def serveBeer (customerAge: Int) = if (customerAge &gt;= 21) println(\"beer\") else println(\"water\")\r\nserveBeer: (customerAge: Int)Unit\r\n \r\nscala&gt; serveBeer(23)\r\nbeer\r\n \r\nscala&gt; serveBeer(19)\r\nwater\r\n<\/pre>\n<p>What we\u2019ve done here is a standard use of conditionals to produce one action or another \u2014 in this case just printing one message or another. The expression in the<strong> if (\u2026)<\/strong> is a Boolean value, either <strong>true<\/strong> or <strong>false<\/strong>. You can see this by just doing the inequality directly:<\/p>\n<pre class=\"brush: scala;\">scala&gt; 19 &gt;= 21\r\nres7: Boolean = false\r\n<\/pre>\n<p>And these expressions can be combined according to the standard rules for conjunction and disjunction of Booleans. Conjunction is indicated with <strong>&amp;&amp;<\/strong> and disjunction with<strong> ||<\/strong>.<\/p>\n<pre class=\"brush: scala;\">scala&gt; 19 &gt;= 21 || 5 &gt; 2\r\nres8: Boolean = true\r\n \r\nscala&gt; 19 &gt;= 21 &amp;&amp; 5 &gt; 2\r\nres9: Boolean = false\r\n<\/pre>\n<p>To check equality, use<strong> ==<\/strong>.<\/p>\n<pre class=\"brush: scala;\">scala&gt; 42 == 42\r\nres10: Boolean = true\r\n \r\nscala&gt; \"the\" == \"the\"\r\nres11: Boolean = true\r\n \r\nscala&gt; 3.14 == 6.28\r\nres12: Boolean = false\r\n \r\nscala&gt; 2*3.14 == 6.28\r\nres13: Boolean = true\r\n \r\nscala&gt; \"there\" == \"the\" + \"re\"\r\nres14: Boolean = true\r\n<\/pre>\n<p>The <em>equality<\/em> operator <strong>==<\/strong> is different from the <em>assignment<\/em> operator <strong>=<\/strong>, and you\u2019ll get an error if you attempt to use <strong>=<\/strong> for equality tests.<\/p>\n<pre class=\"brush: scala;\">scala&gt; 5 = 5\r\n&lt;console&gt;:1: error: ';' expected but '=' found.\r\n5 = 5\r\n^\r\n \r\nscala&gt; x = 5\r\n&lt;console&gt;:10: error: not found: value x\r\nval synthvar$0 = x\r\n^\r\n&lt;console&gt;:7: error: not found: value x\r\nx = 5\r\n^\r\n<\/pre>\n<p>The first example is completely bad because we cannot hope to assign a value to a constant like 5. With the latter example, the error complains about not finding a value <em>x<\/em>. That\u2019s because it is a valid construct, assuming that a <strong>var<\/strong> variable <em>x<\/em> has been previously defined.<\/p>\n<pre class=\"brush: scala;\">scala&gt; var x = 0\r\nx: Int = 0\r\n \r\nscala&gt; x = 5\r\nx: Int = 5\r\n<\/pre>\n<p>Recall that with <strong>var<\/strong> variables, it is possible to assign them a new value. However, it is actually not necessary to use vars much of the time, and there are many advantages with sticking with <strong>vals<\/strong>. I\u2019ll be helping you think in these terms as we go along. For now, try to ignore the fact that vars exist in the language!<\/p>\n<p>Back to conditionals. First, here are more comparison operators:<\/p>\n<div style=\"padding-left: 30px\">x == y   (x is equal to y)<br \/>\nx != y    (x does not equal y)<br \/>\nx &gt; y     (x is larger than y)<br \/>\nx &lt; y     (x is less than y)<br \/>\nx &gt;= y   (x is equal to y, or larger than y)<br \/>\nx &lt;= y   (x is equal to y, or less than y)<\/p>\n<\/div>\n<p>These operators work on any type that has a natural ordering, including Strings.<\/p>\n<pre class=\"brush: scala;\">scala&gt; \"armadillo\" &lt; \"bear\"\r\nres25: Boolean = true\r\n \r\nscala&gt; \"armadillo\" &lt; \"Bear\"\r\nres26: Boolean = false\r\n \r\nscala&gt; \"Armadillo\" &lt; \"Bear\"\r\nres27: Boolean = true\r\n<\/pre>\n<p>Clearly, this isn\u2019t the usual alphabetic ordering you are used to. Instead it is based on ASCII character encodings.<\/p>\n<p>A very beautiful and useful thing about conditionals in Scala is that they return a value. So, the following is a valid way to set the values of the variables <em>x<\/em> and <em>y<\/em>.<\/p>\n<pre class=\"brush: scala;\">scala&gt; val x = if (true) 1 else 0\r\nx: Int = 1\r\n \r\nscala&gt; val y = if (false) 1 else 0\r\ny: Int = 0\r\n<\/pre>\n<p>Not so impressive here, but let\u2019s return to the bartender, and rather than the <strong>serveBeer<\/strong> function printing a String, we can have it return a String representing a beverage, \u201cbeer\u201d in the case of a 21+ year old and \u201cwater\u201d otherwise.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def serveBeer (customerAge: Int) = if (customerAge &gt;= 21) \"beer\" else \"water\"\r\nserveBeer: (customerAge: Int)java.lang.String\r\n \r\nscala&gt; serveBeer(42)\r\nres21: java.lang.String = beer\r\n \r\nscala&gt; serveBeer(20)\r\nres22: java.lang.String = water\r\n<\/pre>\n<p>Notice how the first <strong>serveBeer<\/strong> function returned <strong>Unit<\/strong> but this one returns a String. Unit means that no value is returned \u2014 in general this is to be discouraged for reasons we won\u2019t get into here. Regardless of that, the general pattern of conditional assignment shown above is something you\u2019ll be using a lot.<\/p>\n<p>Conditionals can also have more than just the single <strong>if<\/strong> and <strong>else<\/strong>.  For example, let\u2019s say that the bartender simply serves age appropriate drinks to each customer, and that 21+ get beer, teenagers get soda and little kids should get juice.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def serveDrink (customerAge: Int) = {\r\n|     if (customerAge &gt;= 21) \"beer\"\r\n|     else if (customerAge &gt;= 13) \"soda\"\r\n|     else \"juice\"\r\n| }\r\nserveDrink: (customerAge: Int)java.lang.String\r\n \r\nscala&gt; serveDrink(42)\r\nres35: java.lang.String = beer\r\n \r\nscala&gt; serveDrink(16)\r\nres36: java.lang.String = soda\r\n \r\nscala&gt; serveDrink(6)\r\nres37: java.lang.String = juice\r\n<\/pre>\n<p>And of course, the Boolean expressions in any of the <strong>ifs<\/strong> or <strong>else ifs<\/strong> can be complex conjunctions and disjunctions of smaller expressions. Let\u2019s consider a computational linguistics oriented example now that can take advantage of that, and which we will continue to build on in later tutorials.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>Everybody (hopefully) knows what a part-of-speech is. (If not, go check out Grammar Rock on YouTube.) In computational linguistics, we tend to use very detailed tagsets that go far beyond \u201cnoun\u201d, \u201cverb\u201d, \u201cadjective\u201d and so on. For example, <a href=\"http:\/\/www.mozart-oz.org\/mogul\/doc\/lager\/brill-tagger\/penn.html\">the tagset from the Penn Treebank<\/a> uses NN for singular nouns (table), NNS for plural nouns (tables), NNP for singular proper noun (John), and NNPS for plural proper noun (Vikings).<\/p>\n<p>Here\u2019s an annotated sentence with postags from the first sentence of the Wall Street Journal portion of the Penn Treebank, in the format word\/postag.<\/p>\n<div style=\"padding-left: 30px\"><em>The\/DT index\/NN of\/IN the\/DT 100\/CD largest\/JJS Nasdaq\/NNP financial\/JJ stocks\/NNS rose\/VBD modestly\/RB as\/IN well\/RB .\/.<\/em><br \/>\n<em><br \/>\n<\/em><\/div>\n<p>We\u2019ll see how to process these <em>en masse<\/em> shortly, but for now, let\u2019s build a function that turns single tags like \u201cNNP\u201d into \u201cNN\u201d and \u201cJJS\u201d into \u201cJJ\u201d, using conditionals. We\u2019ll let all the other postags stay as they are.<\/p>\n<p>We\u2019ll start with a suboptimal solution, and then refine it. The first thing you might try is to create a case for every full form tag and output its corresponding shortened tag.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def shortenPos (tag: String) = {\r\n|     if (tag == \"NN\") \"NN\"\r\n|     else if (tag == \"NNS\") \"NN\"\r\n|     else if (tag == \"NNP\") \"NN\"\r\n|     else if (tag == \"NNPS\") \"NN\"\r\n|     else if (tag == \"JJ\") \"JJ\"\r\n|     else if (tag == \"JJR\") \"JJ\"\r\n|     else if (tag == \"JJS\") \"JJ\"\r\n|     else tag\r\n| }\r\nshortenPos: (tag: String)java.lang.String\r\n \r\nscala&gt; shortenPos(\"NNP\")\r\nres47: java.lang.String = NN\r\n \r\nscala&gt; shortenPos(\"JJS\")\r\nres48: java.lang.String = JJ\r\n<\/pre>\n<p>So, it\u2019s doing the job, but there is a lot of redundancy \u2014 in particular, the return value is the same for many cases. We can use disjunctions to deal with this.<\/p>\n<pre class=\"brush: scala;\">def shortenPos2 (tag: String) = {\r\n  if (tag == \"NN\" || tag == \"NNS\" || tag == \"NNP\" || tag == \"NNP\") \"NN\"\r\n  else if (tag == \"JJ\" || tag == \"JJR\" || tag == \"JJS\") \"JJ\"\r\n  else tag\r\n}\r\n<\/pre>\n<p>These are logically equivalent.<\/p>\n<p>There is an easier way of doing this, using properties of Strings. Here, the <strong>startsWith<\/strong> method is very useful.<\/p>\n<pre class=\"brush: scala;\">scala&gt; \"NNP\".startsWith(\"NN\")\r\nres51: Boolean = true\r\n \r\nscala&gt; \"NNP\".startsWith(\"VB\")\r\nres52: Boolean = false\r\n<\/pre>\n<p>We can use this to simplify the postag shortening function.<\/p>\n<pre class=\"brush: scala;\">def shortenPos3 (tag: String) = {\r\n  if (tag.startsWith(\"NN\")) \"NN\"\r\n  else if (tag.startsWith(\"JJ\")) \"JJ\"\r\n  else tag\r\n}\r\n<\/pre>\n<p>This makes it very easy to add an additional condition that collapses all of the verb tags to \u201cVB\u201d. (Left as an exercise.)<\/p>\n<p>A final note of conditional assignments: they can return anything you like, so, for example, the following are all valid. For example, here is a (very) simple (and very imperfect) English stemmer that returns the stem and and suffix.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def splitWord (word: String) = {\r\n|     if (word.endsWith(\"ing\")) (word.slice(0,word.length-3), \"ing\")\r\n|     else if (word.endsWith(\"ed\")) (word.slice(0,word.length-2), \"ed\")\r\n|     else if (word.endsWith(\"er\")) (word.slice(0,word.length-2), \"er\")\r\n|     else if (word.endsWith(\"s\")) (word.slice(0,word.length-1), \"s\")\r\n|     else (word,\"\")\r\n| }\r\nsplitWord: (word: String)(String, java.lang.String)\r\n \r\nscala&gt; splitWord(\"walked\")\r\nres10: (String, java.lang.String) = (walk,ed)\r\n \r\nscala&gt; splitWord(\"walking\")\r\nres11: (String, java.lang.String) = (walk,ing)\r\n \r\nscala&gt; splitWord(\"booking\")\r\nres12: (String, java.lang.String) = (book,ing)\r\n \r\nscala&gt; splitWord(\"baking\")\r\nres13: (String, java.lang.String) = (bak,ing)\r\n<\/pre>\n<p>If we wanted to work with the stem and suffix directly with variables, we can assign them straight away.<\/p>\n<pre class=\"brush: scala;\">scala&gt; val (stem, suffix) = splitWord(\"walked\")\r\nstem: String = walk\r\nsuffix: java.lang.String = ed\r\n<\/pre>\n<h2>             Matching<\/h2>\n<p>Scala provides another very powerful way to encode conditional execution called <em>matching<\/em>. They have much in common with if-else blocks, but come with some nice extra features. We\u2019ll go back to the postag shortener, starting with a full list out of the tags and what to do in each case, like our first attempt with if-else.<\/p>\n<pre class=\"brush: scala;\">def shortenPosMatch (tag: String) = tag match {\r\n  case \"NN\" =&gt; \"NN\"\r\n  case \"NNS\" =&gt; \"NN\"\r\n  case \"NNP\" =&gt; \"NN\"\r\n  case \"NNPS\" =&gt; \"NN\"\r\n  case \"JJ\" =&gt; \"JJ\"\r\n  case \"JJR\" =&gt; \"JJ\"\r\n  case \"JJS\" =&gt; \"JJ\"\r\n  case _ =&gt; tag\r\n}\r\n \r\nscala&gt; shortenPosMatch(\"JJR\")\r\nres14: java.lang.String = JJ\r\n<\/pre>\n<p>Note that the last case, with the underscore \u201c_\u201d is the <em>default<\/em> action to take, similar to the \u201celse\u201d at the end of an if-else block.<\/p>\n<p>Compare this to the if-else function <strong>shortenPos<\/strong> from before, which had lots of repetition in its definition of the form \u201c<strong>else if (tag ==<\/strong> \u201c. Match statements allow you to do the same thing, but much more concisely and arguably, much more clearly. Of course, we can shorten this up.<\/p>\n<pre class=\"brush: scala;\">def shortenPosMatch2 (tag: String) = tag match {\r\n  case \"NN\" | \"NNS\" | \"NNP\" | \"NNPS\" =&gt; \"NN\"\r\n  case \"JJ\" | \"JJR\" | \"JJS\" =&gt; \"JJ\"\r\n  case _ =&gt; tag\r\n}\r\n<\/pre>\n<p>Which is quite a bit more readable than the if-else <strong>shortenPosMatch2<\/strong> defined earlier.<\/p>\n<p>In addition to readability, match statements provide some logical protection. For example, if you accidentally have two cases that overlap, you\u2019ll get an error.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def shortenPosMatchOops (tag: String) = tag match {\r\n|   case \"NN\" | \"NNS\" | \"NNP\" | \"NNPS\" =&gt; \"NN\"\r\n|   case \"JJ\" | \"JJR\" | \"JJS\" =&gt; \"JJ\"\r\n|   case \"NN\" =&gt; \"oops\"\r\n|   case _ =&gt; tag\r\n| }\r\n&lt;console&gt;:10: error: unreachable code\r\ncase \"NN\" =&gt; \"oops\"\r\n<\/pre>\n<p>This is an obvious example, but with more complex match options, it can save you from bugs!<\/p>\n<p>We cannot use the <strong>startsWith<\/strong> method the same way we did with the if-else<strong> shortenPosMatch3<\/strong>. However, we can use regular expressions very nicely with match statements, which we\u2019ll get to in a later tutorial.<\/p>\n<p>Where match statements really shine is that they can match on much more than just the value of simple variables like Strings and Ints.  One use of matches is to check the types of the input to a function that can take a supertype of many types. Recall that <strong>Any<\/strong> is the supertype of all types; if we have the following function that takes an argument with any type, we can use matching to inspect what the type of the argument is and do different behaviors accordingly.<\/p>\n<pre class=\"brush: scala;\">scala&gt; def multitypeMatch (x: Any) = x match {\r\n|    case i: Int =&gt; \"an Int: \" + i*i\r\n|    case d: Double =&gt; \"a Double: \" + d\/2\r\n|    case b: Boolean =&gt; \"a Boolean: \" + !b\r\n|    case s: String =&gt; \"a String: \" + s.length\r\n|    case (p1: String, p2: Int) =&gt; \"a Tuple[String, Int]: \" + p2*p2 + p1.length\r\n|    case (p1: Any, p2: Any) =&gt; \"a Tuple[Any, Any]: (\" + p1 + \",\" + p2 + \")\"\r\n|    case _ =&gt; \"some other type \" + x\r\n| }\r\nmultitypeMatch: (x: Any)java.lang.String\r\n \r\nscala&gt; multitypeMatch(true)\r\nres4: java.lang.String = a Boolean: false\r\n \r\nscala&gt; multitypeMatch(3)\r\nres5: java.lang.String = an Int: 9\r\n \r\nscala&gt; multitypeMatch((1,3))\r\nres6: java.lang.String = a Tuple[Any, Any]: (1,3)\r\n \r\nscala&gt; multitypeMatch((\"hi\",3))\r\nres7: java.lang.String = a Tuple[String, Int]: 92\r\n<\/pre>\n<p>So, for example, if it is an Int, we can do things like multiplication, if it is a Boolean we can negate it (with !), and so on. In the case statement, we provide a new variable that will have the type that is matched, and then after the arrow =&gt;, we can use that variable in a type safe manner. Later we\u2019ll see how to create classes (and in particular case classes), where this sort of matching based function is used regularly.<\/p>\n<p>In the meantime, here\u2019s an example of a simple addition function that allows one to enter a String or Int to specify its arguments. For example, the behavior we desire is this:<\/p>\n<pre class=\"brush: scala;\">scala&gt; add(1,3)\r\nres4: Int = 4\r\n \r\nscala&gt; add(\"one\",3)\r\nres5: Int = 4\r\n \r\nscala&gt; add(1,\"three\")\r\nres6: Int = 4\r\n \r\nscala&gt; add(\"one\",\"three\")\r\nres7: Int = 4\r\n<\/pre>\n<p>Let\u2019s assume that we only handle the spelled out versions of 1 through 5, and that any string we cannot handle (e.g. \u201csix\u201d and aardvark\u201d) is considered to be 0. Then the following two functions using matches handle it.<\/p>\n<pre class=\"brush: scala;\">def convertToInt (x: String) = x match {\r\n  case \"one\" =&gt; 1\r\n  case \"two\" =&gt; 2\r\n  case \"three\" =&gt; 3\r\n  case \"four\" =&gt; 4\r\n  case \"five\" =&gt; 5\r\n  case _ =&gt; 0\r\n}\r\n \r\ndef add (x: Any, y: Any) = (x,y) match {\r\n  case (x: Int, y: Int) =&gt; x + y\r\n  case (x: String, y: Int) =&gt; convertToInt(x) + y\r\n  case (x: Int, y: String) =&gt; x + convertToInt(y)\r\n  case (x: String, y: String) =&gt; convertToInt(x) + convertToInt(y)\r\n  case _ =&gt; 0\r\n}\r\n<\/pre>\n<p>Like if-else blocks, matches can return whatever type you like, including Tuples, Lists and more.<\/p>\n<p>Match blocks are used in many other useful contexts that we\u2019ll come to later. In the meantime, it is also worth pointing out that matching is actually used in variable assignment. We\u2019ve seen it already with Tuples, but it can be done with Lists and other types.<\/p>\n<pre class=\"brush: scala;\">scala&gt; val (x,y) = (1,2)\r\nx: Int = 1\r\ny: Int = 2\r\n \r\nscala&gt; val colors = List(\"blue\",\"red\",\"yellow\")\r\ncolors: List[java.lang.String] = List(blue, red, yellow)\r\n \r\nscala&gt; val List(color1, color2, color3) = colors\r\ncolor1: java.lang.String = blue\r\ncolor2: java.lang.String = red\r\ncolor3: java.lang.String = yellow\r\n<\/pre>\n<p>This is especially useful in the case of the args Array that comes from the command line when creating a script with Scala. For example, consider a program that is run as following.<\/p>\n<pre class=\"brush: bash;\">$ scala nextYear.scala John 35\r\nNext year John will be 36 years old.\r\n<\/pre>\n<p>Here\u2019s how we can do it. (Save the next two lines as nextYear.scala and try it out.)<\/p>\n<pre class=\"brush: scala;\">val Array(name, age) = args\r\nprintln(\"Next year \" + name + \" will be \" + (age.toInt + 1) + \" years old.\")\r\n<\/pre>\n<p>Notice that we had to do <strong>age.toInt<\/strong>. That is because age itself is a String, not an Int.<br \/>\nConditional execution with if-else blocks and match blocks is a powerful part of building complex behaviors into your programs that you\u2019ll see and use frequently!<\/p>\n<p><strong><i>Reference: <\/i><\/strong><a href=\"http:\/\/bcomposes.wordpress.com\/2011\/08\/26\/first-steps-in-scala-for-beginning-programmers-part-3\/\">First steps in Scala for beginning programmers, Part 3<\/a> from our <a href=\"http:\/\/www.javacodegeeks.com\/p\/jcg.html\">JCG partner<\/a> Jason Baldridge at the <a href=\"http:\/\/bcomposes.wordpress.com\/\">Bcomposes<\/a> blog.<\/p>\n<p><strong><i>Related Articles :<\/i><\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-scala-repl-expressions.html\">Scala Tutorial &#8211; Scala REPL, expressions, variables, basic types, simple functions, saving and running programs, comments<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-tuples-lists-methods-on.html\">Scala Tutorial &#8211; Tuples, Lists, methods on Lists and Strings<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-iteration-for.html\">Scala Tutorial &#8211; iteration, for expressions, yield, map, filter, count<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-regular-expressions.html\">Scala Tutorial &#8211; regular expressions, matching<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-regular-expressions_05.html\">Scala Tutorial &#8211; regular expressions, matching and substitutions with the scala.util.matching API<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-maps-sets-groupby.html\">Scala Tutorial &#8211; Maps, Sets, groupBy, Options, flatten, flatMap<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-scalaiosource-accessing.html\">Scala Tutorial &#8211; scala.io.Source, accessing files, flatMap, mutable Maps<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-objects-classes.html\">Scala Tutorial &#8211; objects, classes, inheritance, traits, Lists with multiple related types, apply<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/10\/scala-tutorial-scripting-compiling-main.html\">Scala Tutorial &#8211; scripting, compiling, main methods, return values of functions<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/11\/scala-tutorial-sbt-scalabha-packages.html\">Scala Tutorial &#8211; SBT, scalabha, packages, build systems<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/11\/scala-tutorial-code-blocks-coding-style.html\">Scala Tutorial &#8211; code blocks, coding style, closures, scala documentation project<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/09\/fun-with-function-composition-in-scala.html\">Fun with function composition in Scala<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/08\/how-scala-changed-way-i-think-about-my.html\">How Scala changed the way I think about my Java Code<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/08\/what-features-of-java-have-been-dropped.html\">What features of Java have been dropped in Scala?<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2011\/09\/testing-with-scala.html\">Testing with Scala<\/a><\/li>\n<li><a href=\"http:\/\/www.javacodegeeks.com\/2010\/12\/things-every-programmer-should-know.html\">Things Every Programmer Should Know<\/a><\/li>\n<\/ul>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Preface This is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other resources on the links page of the Computational Linguistics course I\u2019m creating these for. Additionally you can find this and other tutorial series on the JCG Java &hellip;<\/p>\n","protected":false},"author":67,"featured_media":227,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[20],"tags":[235],"class_list":["post-528","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scala","tag-scala-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2011-09-29T08:10:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2012-10-21T20:10:20+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Jason Baldridge\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@http:\/\/twitter.com\/jasonbaldridge\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jason Baldridge\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html\"},\"author\":{\"name\":\"Jason Baldridge\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/95ef2670a4040b0f7101c48dba2795c0\"},\"headline\":\"Scala Tutorial &#8211; conditional execution with if-else blocks and matching\",\"datePublished\":\"2011-09-29T08:10:00+00:00\",\"dateModified\":\"2012-10-21T20:10:20+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html\"},\"wordCount\":1783,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/scala-logo.jpg\",\"keywords\":[\"Scala Tutorial\"],\"articleSection\":[\"Scala\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html\",\"name\":\"Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/scala-logo.jpg\",\"datePublished\":\"2011-09-29T08:10:00+00:00\",\"dateModified\":\"2012-10-21T20:10:20+00:00\",\"description\":\"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/scala-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/scala-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2011\\\/09\\\/scala-tutorial-conditional-execution.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JVM Languages\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/jvm-languages\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Scala\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/jvm-languages\\\/scala\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Scala Tutorial &#8211; conditional execution with if-else blocks and matching\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/95ef2670a4040b0f7101c48dba2795c0\",\"name\":\"Jason Baldridge\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g\",\"caption\":\"Jason Baldridge\"},\"sameAs\":[\"http:\\\/\\\/bcomposes.wordpress.com\\\/\",\"http:\\\/\\\/www.linkedin.com\\\/pub\\\/jason-baldridge\\\/5\\\/629\\\/9b2\",\"https:\\\/\\\/x.com\\\/http:\\\/\\\/twitter.com\\\/jasonbaldridge\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/jason-baldridge\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks","description":"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html","og_locale":"en_US","og_type":"article","og_title":"Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks","og_description":"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other","og_url":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2011-09-29T08:10:00+00:00","article_modified_time":"2012-10-21T20:10:20+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg","type":"image\/jpeg"}],"author":"Jason Baldridge","twitter_card":"summary_large_image","twitter_creator":"@http:\/\/twitter.com\/jasonbaldridge","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Jason Baldridge","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html"},"author":{"name":"Jason Baldridge","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/95ef2670a4040b0f7101c48dba2795c0"},"headline":"Scala Tutorial &#8211; conditional execution with if-else blocks and matching","datePublished":"2011-09-29T08:10:00+00:00","dateModified":"2012-10-21T20:10:20+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html"},"wordCount":1783,"commentCount":1,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg","keywords":["Scala Tutorial"],"articleSection":["Scala"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html","url":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html","name":"Scala Tutorial - conditional execution with if-else blocks and matching - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg","datePublished":"2011-09-29T08:10:00+00:00","dateModified":"2012-10-21T20:10:20+00:00","description":"PrefaceThis is part 3 of tutorials for first-time programmers getting into Scala. Other posts are on this blog, and you can get links to those and other","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/scala-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2011\/09\/scala-tutorial-conditional-execution.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"JVM Languages","item":"https:\/\/www.javacodegeeks.com\/category\/jvm-languages"},{"@type":"ListItem","position":3,"name":"Scala","item":"https:\/\/www.javacodegeeks.com\/category\/jvm-languages\/scala"},{"@type":"ListItem","position":4,"name":"Scala Tutorial &#8211; conditional execution with if-else blocks and matching"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/95ef2670a4040b0f7101c48dba2795c0","name":"Jason Baldridge","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/b755d282f869512990e0ce9118c71ccd859fad42163f8e5d62d180ea42ea9720?s=96&d=mm&r=g","caption":"Jason Baldridge"},"sameAs":["http:\/\/bcomposes.wordpress.com\/","http:\/\/www.linkedin.com\/pub\/jason-baldridge\/5\/629\/9b2","https:\/\/x.com\/http:\/\/twitter.com\/jasonbaldridge"],"url":"https:\/\/www.javacodegeeks.com\/author\/jason-baldridge"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/528","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/67"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=528"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/528\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/227"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=528"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=528"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=528"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}