{"id":4732,"date":"2017-03-26T19:41:51","date_gmt":"2017-03-26T19:41:51","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=4732"},"modified":"2017-03-26T19:41:51","modified_gmt":"2017-03-26T19:41:51","slug":"learning-scala-day-1","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/learning-scala-day-1\/","title":{"rendered":"Learning Scala &#8211; day 1"},"content":{"rendered":"<p>I&#8217;ve decided to learn (at least the basics) of Scala. This post will cover the standard programming constructs and features, whilst not intended to be in depth, it will act as an entry into using Scala or a reminder for myself.<\/p>\n<p><em>Note: I will be writing this post as somebody who comes from a C# background and has also used F#. So, sorry if you&#8217;re reading this and thinking &#8220;I don&#8217;t know what F# would look like&#8221; for example.<\/em><\/p>\n<p><strong>val and var<\/strong><\/p>\n<p>A <em>val<\/em> is immutable whereas a <em>var<\/em> is not. Hence assuming we have the following<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nobject Calculator {\r\n  def add(a: Int, b: Int): Int = {\r\n      a + b\r\n  }\r\n\r\n  def subtract(a: Int, b: Int): Int = {\r\n    a - b\r\n  }\r\n}\r\n<\/pre>\n<p>The we can assign our val thus<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nval calc = Calculator\r\n\r\n\/\/ this line will error\r\ncalc = Calculator\r\n<\/pre>\n<p>whereas our var will allow reassignment, hence<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nvar calc = Calculator\r\n\r\n\/\/ this line will success\r\ncalc = Calculator\r\n\r\n<\/pre>\n<p>Simple enough.<\/p>\n<p><strong>Types<\/strong><\/p>\n<p>I&#8217;m not going to list all the types supported in Scala &#8211; ofcourse we have Int, String etc. What I will say though, is like F#, a type may be inferred or we might specify the type where a hint is required<\/p>\n<p>Let&#8217;s see how we can use a type<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nval inferredString = &quot;Hello&quot;\r\nval explcitString : String = &quot;Hello&quot;\r\n<\/pre>\n<p>We declare a type after the name of the val\/var, as per the example above. <\/p>\n<p>There&#8217;s an ultimate base type in Scala (a little like object in C#) and this is called <em>Any<\/em>. According to <a href=\"http:\/\/ktoso.github.io\/scala-types-of-types\/\">Unified Type System<\/a> this <em>Any<\/em> type is not the same as the <em>java.lang.Object<\/em>. In Scala we have <em>AnyRef<\/em> which IS analogous to <em>java.lang.Object<\/em> whereas <em>AnyVal<\/em> is the equivalent base of value types. Ofcourse <em>Any<\/em> is the base of both <em>AnyValue<\/em> and <em>AnyRef<\/em>.<\/p>\n<p>Like F#, Scala prefers the idea of a <em>Nothing<\/em> value than a <em>null<\/em> but (again like F#) null is also supported.<\/p>\n<p>Scala, ofcourse, supports collections and arrays. <\/p>\n<p>We can declare and array with type expected type or inferred, for example, these two arrays create the same type of array<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\n\/\/ explicit\r\nval a = Array&#x5B;String](&quot;a&quot;, &quot;b&quot;)\r\n\/\/ inferred\r\nval b = Array(&quot;a&quot;, &quot;b&quot;)\r\n<\/pre>\n<p>To access\/alter an array at a given index we again use brackets (), i.e.<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nval a = Array(&quot;a&quot;, &quot;b&quot;)\r\n\/\/ amend &quot;b&quot; to &quot;c&quot;\r\na(1) = &quot;c&quot;\r\n<\/pre>\n<p><strong>Return values<\/strong><\/p>\n<p>When a method returns a value we can use the return function, for example <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\ndef result : Int = {\r\n   return(123)\r\n}\r\n<\/pre>\n<p>or without parenthesis, i.e. <em>return 123<\/em> or, like F# the return can also be the last line of the function, i.e.<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\ndef result : Int = {\r\n   123\r\n}\r\n<\/pre>\n<p>and with the type being inferred we can reduce this further to <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\ndef result = {\r\n   123\r\n}\r\n<\/pre>\n<p><strong>Loops<\/strong><\/p>\n<p>The <em>for<\/em> loop, using the <em>to<\/em> function, for example <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nfor(i &lt;- 1 to 3) {\r\n   print(i);\r\n}\r\n\r\n\/\/ will print\r\n\/\/ 123\r\n<\/pre>\n<p>The <em>for<\/em> loop, using the <em>until<\/em> method<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nfor(i &lt;- 1 until 3) {\r\n   print(i);\r\n}\r\n\r\n\/\/ will print\r\n\/\/ 12\r\n<\/pre>\n<p><em>to<\/em> and <em>until<\/em> are methods, hence we could use the following syntax<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nfor(i &lt;- 1 to 3) {}\r\nfor(i &lt;- 1 to.(3)) {}\r\nfor(i &lt;- 1.to(3)) {}\r\n<\/pre>\n<p>each of the above does the same thing, just with different syntax. What each of these methods does is return a Range, for example, in the the following code <em>r<\/em> is of type Range<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nval r = 1.to(3)\r\n\r\nfor(i &lt;- r) {\r\n   print(i)\r\n}\r\n<\/pre>\n<p>It&#8217;s always worth noting the <em>i<\/em> is a val (hence immutable) type and is created each time through the loop. <\/p>\n<p><em>Note: So how can &#8220;to&#8221; and &#8220;until&#8221; be used without parenthesis? If a method is zero or one arguments, we do not need the parenthesis. Therefore, if we have code like this<\/em><\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nobject Calculator {\r\n  def inc(a : Int): Int = {\r\n    a + 1\r\n  }\r\n}\r\n\r\n\/\/ we can do this\r\n\r\nval calc = Calculator\r\nval r = calc inc 2\r\n<\/pre>\n<p>Back to loops, so we have a <em>for<\/em> loop, we&#8217;ve also got <em>while<\/em> loops so <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nvar i = 0\r\nwhile(i &lt; 3) {\r\n   print(i)\r\n   i = i + 1\r\n}\r\n<\/pre>\n<p>as well as <em>do&#8230;while<\/em><\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nvar i = 0\r\ndo {\r\n   print(i)\r\n   i = i + 1\r\n} while(i &lt; 3)\r\n<\/pre>\n<p>like C#\/Java we can also <em>break<\/em> out of a loop, however this keyword is not part of Scala. To use, we need to import the functionality using <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport scala.util.control._\r\n\r\nvar i = 0\r\nwhile(true) {\r\n   print(i)\r\n   i = i + 1\r\n   if(i == 3)\r\n      Breaks.break\r\n}\r\n<\/pre>\n<p><strong>Importing functionality\/libraries<\/strong><\/p>\n<p>As you&#8217;ve seen with the <em>Breaks.break<\/em> method, we can import functionality as we do in C# with using and import in Java, like this <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport scala.util.control._\r\n<\/pre>\n<p>The use of the _ is like a saying import everything within the scala.util.control namespace and we&#8217;ll then use code like <em>Breaks.break<\/em> to call the method, but we could also be more explicit and change our code to be like this <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport scala.util.control.Breaks.break\r\n\r\n\/\/ other code\r\nif(i == 3)\r\n   break\r\n<\/pre>\n<p>Like F# being built atop .NET and therefore allowing us access to a rich framework and eco-system, Scala is built upon Java and hence allows us access to it&#8217;s rich set of frameworks etc.<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport java.util.Date\r\n\r\ndef output  = print(new Date() + &quot;:&quot; + msg)\r\n<\/pre>\n<p>in the above, it&#8217;s probably obvious, we&#8217;re using the Java Date class, we can import multiple specific classes like this <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport java.util.{Date, Locale}\r\n<\/pre>\n<p>or for all (as already seen)<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nimport java.util._\r\n<\/pre>\n<p><strong>Classes and Objects<\/strong><\/p>\n<p>We can define a class as follows<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nclass Report(msg: String) {\r\n\r\n  def output = println(msg)\r\n}\r\n<\/pre>\n<p>By default (i.e. without an scope declaration) classes are public, we could prefix the class thus <em>private class Report<\/em> to change from the default.<\/p>\n<p>The <em>msg: String<\/em> is like a constructor (a similar design came up for <a href=\"https:\/\/github.com\/dotnet\/roslyn\/issues\/6997\" target=\"_blank\">Primary constructors<\/a> in C# 6) but we can also create overload for the constructor like this<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nclass Report(msg: String) {\r\n\r\n  def this(msg: String, num: Int) = this(msg + &quot;  &quot; + num.toString)\r\n  def this(num: Int, msg: String) = this(msg + &quot;  &quot; + num.toString)\r\n\r\n  def output = println(msg)\r\n}\r\n<\/pre>\n<p>We can also define an <em>object<\/em> like this <\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nobject Report {\r\n\r\n  def output(msg: String) = println(msg)\r\n}\r\n<\/pre>\n<p>In scala this is known as a singleton object, I would say similar to a static class in C#. Hence does not have a constructor as we cannot create an instance of <em>Report<\/em> and we do not use the <em>new<\/em> keyword to use it, i.e.<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nval s = Report\r\ns.output(&quot;Hi&quot;)\r\n<\/pre>\n<p>It&#8217;s also possible to associate an <em>object<\/em> with a <em>class<\/em>, for example<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nclass Report(msg: String) {\r\n\r\n  def this(msg: String, num: Int) = this(msg + &quot;  &quot; + num.toString)\r\n  def this(num: Int, msg: String) = this(msg + &quot;  &quot; + num.toString)\r\n\r\n  def output  = Report output(this.msg)\r\n}\r\n\r\nobject Report {\r\n  def output(msg: String) = println(msg)\r\n}\r\n<\/pre>\n<p>This pairing of <em>class<\/em> with an <em>object<\/em> is known as a companion class and vice versa we can think of the object as the companion object. In the example above, we&#8217;ve defined the equivalent of a static method in the object and the class output calls this. Obviously this is a slightly convoluted example, but another use is that the object might include (for example) private fields which are used from the class, like this<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nclass Report(msg: String) {\r\n\r\n  def this(msg: String, num: Int) = this(msg + &quot;  &quot; + num.toString)\r\n  def this(num: Int, msg: String) = this(msg + &quot;  &quot; + num.toString)\r\n\r\n  def output  = print(Report.name + &quot;:&quot; + msg)\r\n}\r\n\r\nobject Report {\r\n  private def name = &quot;Report&quot;\r\n}\r\n<\/pre>\n<p>alternatively, we can <em>import<\/em> the object and remove the need to prefix use of <em>name<\/em> with <em>Report<\/em> &#8211; like this<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nclass Report(msg: String) {\r\n\r\n  import Report._\r\n\r\n  def this(msg: String, num: Int) = this(msg + &quot;  &quot; + num.toString)\r\n  def this(num: Int, msg: String) = this(msg + &quot;  &quot; + num.toString)\r\n\r\n  def output  = print(name + &quot;:&quot; + msg)\r\n}\r\n\r\nobject Report {\r\n  private def name = &quot;Report&quot;\r\n}\r\n<\/pre>\n<p><strong>Commenting code<\/strong><\/p>\n<p>As you&#8217;ve seen in some of the examples, scala supports \/\/ for single line comments as well as the standard (at least in C style languages) \/* *\/<\/p>\n<p>We can also support <a href=\"http:\/\/docs.scala-lang.org\/style\/scaladoc.html\" target=\"_blank\">scaladoc<\/a> comments, these use \/** *\/ for example<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\n\/**\r\nThis is a report\r\n*\/\r\nclass Report(msg: String) {\r\n}\r\n<\/pre>\n<p>In Intelli> (for example) selecting the Report when used in our code and pressing ctrl+q will result in a popup which will display the documentation for the class, the text with \/** *\/ will be displayed as documentation.<\/p>\n<p><strong>Whoa, hold on, how about an application<\/strong><\/p>\n<p>So for all of the above, I&#8217;ve talked about the language, for these examples I&#8217;ve used <a href=\"http:\/\/import java.util._\" target=\"_blank\">ScalaTest<\/a> but what about an entry point for an application.<\/p>\n<p>Ofcourse we have <em>main<\/em> and we can create our application object like this<\/p>\n<pre class=\"brush: scala; title: ; notranslate\" title=\"\">\r\nobject MyApp {\r\n  def main(args: Array&#x5B;String]): Unit = {\r\n     println(&quot;Hello World&quot;)\r\n   }\r\n}\r\n<\/pre>\n<p>As you&#8217;ll recall from the section on classes and objects, this is similar to a singleton class with, what we might view as, a static method.<\/p>\n<p>This requires the <em>args : Array[String])<\/em> and must return a void\/Unit<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve decided to learn (at least the basics) of Scala. This post will cover the standard programming constructs and features, whilst not intended to be in depth, it will act as an entry into using Scala or a reminder for myself. Note: I will be writing this post as somebody who comes from a C# [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[165],"tags":[],"class_list":["post-4732","post","type-post","status-publish","format-standard","hentry","category-scala"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4732","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=4732"}],"version-history":[{"count":17,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4732\/revisions"}],"predecessor-version":[{"id":4778,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/4732\/revisions\/4778"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=4732"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=4732"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=4732"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}