<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Heres on Medium]]></title>
        <description><![CDATA[Stories by Alex Heres on Medium]]></description>
        <link>https://medium.com/@alessandroheres?source=rss-6ae42849bfe4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Alex Heres on Medium</title>
            <link>https://medium.com/@alessandroheres?source=rss-6ae42849bfe4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:19:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alessandroheres/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scala: Useful User Information + Why you should consider the Language]]></title>
            <link>https://medium.com/@alessandroheres/scala-useful-user-information-why-you-should-consider-the-language-f6ef23bd3052?source=rss-6ae42849bfe4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ef23bd3052</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Heres]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 13:23:44 GMT</pubDate>
            <atom:updated>2019-04-22T13:23:44.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmGwgWm0TcMHfNmXe6g4Mw.jpeg" /></figure><p>In general, becoming proficient in Scala is a benefit for many reasons: It is a multi-paradigm language (functional, object-oriented) with syntax closely resembling that of Java, and even has access Java libraries and compiles programs on a JVM. In this post, we look over the lesser-known benefits of Scala, and why one might consider using the language to approach a task or project.</p><h3>Benchmarking Speed</h3><p>In terms of execution speed, we already know Scala has great benefits since it is a compiled language. But how does it stack up to other compiled languages, such as C++ and Java? To measure this, we will run a benchmark on 3 languages and compare the times of each.</p><h4>The Test</h4><p>What we will do to compare the benchmarking speeds of 2 programming languages, is run the same program in both languages, making sure to capture the time take to execute the program entirely. Specifically, we will see how long each language takes to run ten million unsuccessful binary searches.</p><p>For each language, we will use an iterative binary search algorithm to perform unsuccessful searches on a large array of integers, size 2097152. We are interested in the time it takes for the binary searches only, so we make sure not to include the instantiation times for the array, etc.</p><p>The algorithm will run 10 times on each language, where we can collect an average. We will also try to match the syntax between languages as closely as possible.</p><h4>Scala Program and Results</h4><p>The following is the Scala source code we used to run our experiment:</p><pre>object MyProgram extends App {<br> def iterativeBinarySearch(list: Array[Int], target: Int): Int = {<br>   var left = 0<br>   var right = list.length - 1<br>   while (left &lt;= right) {<br>     val mid = left + (right - left) / 2<br>     if (list(mid) == target)<br>       return mid<br>     else if (list(mid) &gt; target)<br>       right = mid - 1<br>     else<br>       left = mid + 1<br>   }<br>   -1<br> }<br><br> def tenMillionSearches(numList: Array[Int], numListSize: Int): Unit = {<br>   var avg: Double = 0<br>   print(&quot;Times for 10,000,000 unsuccessful binary searches on array of size &quot; + numListSize + &quot;: \n&quot;)<br>   for (i &lt;- 1 to 10) {<br>     val begin = System.currentTimeMillis<br><br>     for (j &lt;- 0 until 10000000) {<br>       iterativeBinarySearch(numList, 1)<br>     }<br><br>     val elapsedTime = System.currentTimeMillis - begin<br>     avg += elapsedTime<br><br>     print(&quot;Trial #&quot; + i + &quot;: &quot; + elapsedTime + &quot; milliseconds.\n&quot;)<br>   }<br><br>   avg /= 10<br>   print(&quot;Time for 10,000,000 unsuccessful binary searches on array of size &quot; + numListSize + &quot;, averaged over 10 runs: &quot; + avg + &quot; milliseconds.\n&quot;)<br><br> }<br><br> val arr = Array.fill(2097152)(0)<br> tenMillionSearches(arr, 2097152)<br>}</pre><p>Running the program above, we obtain the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*kCylQhKMnttEgS8OG5MeGw.png" /></figure><h4>Scala vs. C++</h4><p>Now we write the same program in C++. We have the following C++ code:</p><pre>#include &lt;iostream&gt;<br>#include &lt;time.h&gt;<br><br>int iterativeBinarySearch(int arr[], int size, int key)<br>{<br> int lowerBound = 0;<br> int higherBound = size - 1;<br><br> while (lowerBound &lt;= higherBound)<br> {<br>  int middle = (lowerBound + higherBound) / 2;<br><br>  if (arr[middle] == key)<br>   return middle;<br><br>  else if (arr[middle] &gt; key)<br>   higherBound = middle - 1;<br><br>  else<br>   lowerBound = middle + 1;<br> }<br> return -1;<br>}<br><br>void tenMillionSearches(int numList[], int numListSize)<br>{<br> double avg = 0;<br> <br> std::cout &lt;&lt; &quot;Times for 10,000,000 unsuccessful binary searches on array of size &quot; &lt;&lt; numListSize &lt;&lt; &quot;: &quot; &lt;&lt; std::endl;<br> for (int i = 0; i &lt; 10; i++)<br> {<br>  clock_t begin = clock();<br>  for (int j = 0; j &lt; 10000000; j++)<br>   iterativeBinarySearch(numList, numListSize, 1);<br><br>  double elapsed_secs = double(clock() - begin) / CLOCKS_PER_SEC;<br>  avg += elapsed_secs;<br>  std::cout &lt;&lt; &quot;Trial #&quot; &lt;&lt; i + 1 &lt;&lt; &quot;: &quot; &lt;&lt; elapsed_secs &lt;&lt; &quot; seconds.&quot; &lt;&lt; std::endl;<br> }<br><br> avg /= 10;<br> std::cout &lt;&lt; &quot;Time for 10,000,000 unsuccessful binary searches on array of size &quot; &lt;&lt; numListSize &lt;&lt; &quot;, averaged over 10 runs: &quot; &lt;&lt; avg &lt;&lt; &quot; seconds.&quot; &lt;&lt; std::endl;<br>}<br><br>int main()<br>{<br> int* arr = new int[2097152];<br> tenMillionSearches(arr, 2097152);<br> delete[] arr;<br><br> system(&quot;pause&quot;);<br> return 0;<br>}</pre><p>We have the following results from our program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*P8Y_f98yk9b0x-saUiQaQw.png" /></figure><p>By direct comparison of our timings, the C++ times are almost twice as long as our Scala times.</p><h4>Scala vs. Java</h4><p>Finally, we’ll write our program for another JVM language: Java.</p><pre>public class BinarySearch {<br><br> int binarySearch(int arr[], int x) {<br>        int l = 0, r = arr.length - 1;<br>        while (l &lt;= r) {<br>            int m = l + (r-l)/2;<br> <br>            if (arr[m] == x)<br>                return m;<br> <br>            if (arr[m] &lt; x)<br>                l = m + 1;<br> <br>            else<br>                r = m - 1;<br>        }<br>        return -1;<br>    }<br> <br> void tenMillionSearches(BinarySearch bs, int numList[]) {<br>  double avg = 0;<br>  <br>  System.out.println(&quot;Times for 10,000,000 unsuccessful binary searches on array of size &quot; + numList.length + &quot;: \n&quot;);<br>  for(int i = 0; i &lt; 10; i++) {<br>   long start = System.currentTimeMillis();<br>   for (int j = 0; j &lt; 10000000; j++) {<br>    bs.binarySearch(numList, 1);<br>   }<br>  <br>   double elapsed = (System.currentTimeMillis() - start) / 1000.0;<br>   avg += elapsed;<br>   System.out.println(&quot;Trial #&quot; + (i + 1) + &quot;: &quot; + elapsed + &quot; seconds.&quot;);<br>  }<br>  avg /= 10;<br>  System.out.println(&quot;Time for 10,000,000 unsuccessful binary searches on array of size &quot; + numList.length + &quot;, averaged over 10 runs: &quot; + avg + &quot; seconds.&quot;);<br> <br> }<br> <br> public static void main(String[] args) {<br>  BinarySearch bs = new BinarySearch();<br>  int arr[] = new int[2097152];<br>  <br>  bs.tenMillionSearches(bs, arr);<br>  arr = null;<br> }<br>}</pre><p>With Java, we obtain the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*9K8v1j0EaZ7ATFXEv0gwVQ.png" /></figure><p>These are our fastest times yet, just slightly faster than those of Scala. Out of our three tested languages, C++ had the slowest times, while Java had the fastest.</p><p>Scala’s performance in this simple benchmark was actually pretty good compared to other compiled languages, and was among one of the fastest.</p><h3>Safety</h3><p>Programmers can make all kinds of mistakes; copy-paste errors, code typos, typing errors, you name it. Depending on the mistake, the impacting consequence can vary. <strong>Safety</strong> is the application of programming practices that prevent these kinds, including <strong>type safety </strong>to prevent type errors.</p><p>In general, we try to make the most out of what we know about our values at compile-time to minimize the consequences of these mistakes.</p><h4>Avoiding Null</h4><p>In a compiled language with a type-checker, like Scala, many such mistakes are caught before you even run your code by the compiler. Passing in the wrong type such as an int when a string was expected results in a type-error. Passing in null when no-null was expected results in an error that is not caught by the compiler.</p><h4>Avoiding Side Effects</h4><p>Side effects in Scala are not detected by the compiler, and can lead to serious program errors. Let us look at an example.</p><pre>var result = 0<br><br>for (i &lt;- 0 until 10) {<br>  result += i<br>}<br><br>if (result &gt; 10) result = result + 5 <br><br>println(result) // 50<br>makeUseOfResult(result)</pre><p>Here, the result variable is calculated via mutations (i.e. where result is incremented) and prepared for use with the makeUseOfResult function. But what if makeUseOfResult receives some invalid input produced by a particular mutation, or the lack thereof?</p><pre>var result = 0<br><br>for (i &lt;- 0 until 10) {<br>  results += i<br>} <br><br>println(result) // 45<br>makeUseOfResult(result) // invalid input!</pre><p>A good solution to this problem would be to eliminate the <strong>side effects</strong>, while specifying each stage of the result variable such that we eliminate the ambiguity of possible errors:</p><pre>val summed = (0 until 10).sum<br><br>val result = if (summed &gt; 10) summed + 5 else summed<br><br>println(result) // Compilation Failed: not found: value result<br>makeUseOfResult(result)</pre><p>Note that this does not make your code ‘invincible’. For example, using the result<strong> </strong>variable before its ready, even indirectly, will lead to a compilation error.</p><h4>Structured Data and Variance</h4><p>We have covered variance a little bit in the past, and know that the use of variance in the type system allows us to make intuitive connections between complex types. For example:</p><ul><li>A covariant class <strong>Foo[+A]</strong> implies that for two types A and B where A is a subtype of B, then List[A] is a subtype of List[B].</li><li>A contravariant class <strong>Foo[-A]</strong> implies that for two types A and B where A is a subtype of B, List[B] is a subtype of List[A].</li><li>An invariant class <strong>Foo[A]</strong> is the default of generic classes in Scala. A <strong>Foo[A]</strong> is not a <strong>Foo[B]</strong>, nor is the reverse true.</li></ul><p>Using variance to our advantage, we can specifically define classes that have a more-complex relationship of its objects. For a more detailed explanation of class variance in Scala, please check out the <a href="https://docs.scala-lang.org/tour/variances.html">official documentation</a>.</p><h3>Ease of Use</h3><p>Scala is an accessible language in that it is easy to start programming in the language right away, even if you do not have the language or its requirements installed.</p><h4>Running Scala Programs without an Installation</h4><p>If you are looking to run some Scala code but your machine lacks the required build tools, worry not for there is <a href="https://scastie.scala-lang.org/">Scasti</a>.</p><p><strong>Scastie</strong> is an simple online Scala IDE with substantial configuration options. Programs compiled with Scastie are built using sbt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fzp-GCmgDUzF1tkt4sN2YA.png" /></figure><p>In the <strong>Build Settings</strong> tab, you can change the following information:</p><ul><li>The Target Compiler (set to Scalac by default)</li><li>Scala Version (set to 2.12.8 by default)</li><li>Libraries to Include in Project</li><li>Sbt Configuration (build.sbt file settings)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*bx8LD4P7emWV1zqI0nQI1w.png" /></figure><p>Alternatively, if you are interested in installing the tools needed write Scala programs straight from your machine’s command line, you can refer to our <a href="https://medium.com/@alessandroheres/scala-programming-an-introduction-33464b390d57">installation guide</a>.</p><h4>Intuitive Syntax, and Up-To-Date Documentation</h4><p>Scala is very similar to Java in syntax. Though in Scala, the semicolon at the end of lines is optional.</p><ul><li><strong>Case Sensitivity</strong> — As with most programming languages, case sensitivity exists in Scala. If you have Foo and foo, they would have different meanings.</li><li><strong>Program file name</strong> — the program file should match the object name. If this does not match, the program will not compile.</li></ul><p>Currently, the Scala language is up to version 2.13.0, and many previous versions of the language can be found <a href="https://www.scala-lang.org/download/all.html">here</a>. For each of these versions, there is extensive documentation and APIs that can be found <a href="https://docs.scala-lang.org/api/all.html">here</a>.</p><p>Since each version’s documentation is available with great community support, a lot of the versions are viable options to choose to use for a project, though we generally recommend one of the more recent versions.</p><h3>Memory Footprint</h3><p>In terms of performance, the next most important concept alongside time complexity, is space complexity.</p><h4>Data Types and Their Sizes</h4><p>The following table lists Scala data types along with their sizes and ranges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*dkRsh47OCHOlilL3DAYrlw.png" /></figure><h3>Why You Should Write in Scala</h3><p>Scala is a powerful language which combines the functionalities of functional as well as object oriented programming languages.Functions, macros, and tuples are some of those functionalities.Scala’s complex features promote better coding and performance increase.</p><p>Scala was introduced in 2003 to address many of the concerns associated with Java. the language was built on top of the Java Virtual Machine to offer compatibility with Java and Interoperability. According to Google’s run-time measurements:</p><ul><li>Scala provides code complexity optimization</li><li>It offers concise notation</li></ul><p>Testing and development in Scala are also amplified as a result of developers utilizing strength of both object oriented and functional coding paradigms. Also, it can perform the same tasks as Java with less lines of code. An obvious question arises, why can’t we simply shorten the code in Java? That is possible but the methods would break away from standard practice and makes it harder to read.</p><p>Scala has a learning curve i.e it takes a while to master this language but it adds to Java and make it more functional. Some of the features introduced by Scala are:</p><ul><li>String comparison advancements</li><li>Pattern matching</li><li>Mixins, which incorporate functions in class definitions.</li><li>Class variance</li></ul><p>Scala is a fun learning experience that a lot of developers compare with other languages. It is accessible and well-documented which makes it a good decision for developers with varied levels of experience. It also includes a full fledged API library. It is easier to code, test, debug and deploy a scalable software. For any software and program using Scala never affects the performance adversely. It is versatile and can be used to develop desktop software, games, web apps, mobile solutions and software as a service. Klout, LinkedIn, Amazon, Blizzard, Coursera, Twitter are using Scala now a days. It offers clean code, advanced features, functional and object-oriented programming in an open-source package that leverages Java’s environment.</p><h3>Authors</h3><p>Alessandro Heres — <a href="https://github.com/alexheres">Github</a><br>Tristen Sprainis — <a href="https://github.com/Tsprainis">Github</a><br>Ayushi Priyadarshi — <a href="https://github.com/ayupriya">Github</a> | <a href="https://www.linkedin.com/in/ayushi-priyadarshi-21b237145">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ef23bd3052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala: Internals and Intermediates]]></title>
            <link>https://medium.com/@alessandroheres/scala-internals-and-intermediates-483e654bb6d2?source=rss-6ae42849bfe4------2</link>
            <guid isPermaLink="false">https://medium.com/p/483e654bb6d2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Alex Heres]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 04:04:13 GMT</pubDate>
            <atom:updated>2019-04-01T04:07:19.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*s2xqo7Ji3vpTpIUw3cooyw.png" /></figure><p>In our previous Scala guides, we covered Scala on a very external level; installation, syntax and semantics, debugging and unit testing. In this guide, we aim to explore Scala’s toolchain and internals.</p><p>Finally, please ensure that you have installed both <strong>Scala </strong>and <strong>scalac</strong>, the language and its compiler respectively. This means you will also need the Java Development Kit (JDK), preferably JDK8. If you require assistance in setting up any of these, you can refer to our <a href="https://medium.com/@alessandroheres/scala-programming-an-introduction-33464b390d57">Scala installation guide</a>.</p><h3>Toolchains and the Scala Compiler (scalac)</h3><p>A <strong>toolchain</strong> is a set of ‘chained’ software development tools used to perform complex software development tasks or create software products, including program compilation, debugging, etc.</p><p>The Scala Compiler, or <strong>scalac</strong>,<strong> </strong>performs a ton of work so your program can be portable and successfully executed on any target machine. Recall that Scala runs on the Java Virtual Machine (JVM). Then the purpose of <strong>scalac</strong> is to parse your high-level code, and generate the corresponding portable JVM bytecode with the help of abstract syntax trees (AST), among loading in packages and other important compilation tasks.</p><p>A fresh installation of <strong>Scala</strong> and <strong>scalac</strong> already comes packaged with an efficient toolchain for compilation, which we examine in the following section.</p><h4>Using Compiler Options</h4><p>There are two primary ways to use compiler options:</p><ol><li>Using <strong>scalac</strong> — Simply write the following command into your terminal:</li></ol><pre>scalac [ &lt;options&gt; ] &lt;source files&gt;</pre><p>Where [ &lt;options&gt; ] is the list of options you desire, and &lt;source files&gt; are your Scala files to be examined.</p><p>2. Using <strong>sbt</strong> — In your sbt project’s build.sbt file, we add the following code:</p><pre>scalacOptions ++= Seq(<br> “-option1”, “arg1”, // Option and arguments on same line<br> “-option2”, // New lines for each options<br> “-option3”<br>)</pre><p>In the scalacOptions body, each option on its own line, and any arguments for our options are on the same line. All specified options and arguments are of the String type.</p><p>In this guide, we will be using <strong>scalac</strong> to explore the compiler.</p><h4>Compilation Phases</h4><p>Fortunately, <strong>scalac</strong> supports compiler options that let us peek at each individual compilation phase of our Scala project. Open up your project in the scalac command line, and execute the following option:</p><pre>scalac -Xshow-phases</pre><p>This should print a rather long table of compilation phases, along with their IDs and descriptions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*4SBPmAsFDtPu1yLyaBsL5w.png" /></figure><p>At the time of this writing, these are the 24 compilation phases of <strong>scalac</strong> and their duties. These are the necessary steps to turning your high-level Scala code into a portable, intermediate representation known as JVM bytecode to be successfully executed by the JVM on your target platform.</p><p>Throughout the compilation process, <strong>scalac</strong> builds and modifies ASTs in order to produce the JVM bytecode. For example, consider the following simple program of a for loop:</p><pre>object MyProgram extends App {<br>  class aFunctionDef (num: Int) {<br>    def ForLoopFunction(): Unit = {<br>      for (i &lt;- 1 to num) {<br>        if (i % 2 == 0)<br>          println(i.toString + “: even”)<br>        else<br>          println(i.toString + “: odd”)<br>      }<br>    }<br>  }</pre><pre>  var testClass = new aFunctionDef(5)<br>  testClass.ForLoopFunction()<br>  println(“End of Test Program.”)<br>}</pre><p>We can actually view the evolution of the AST generated for our Scala program at each compilation phase! Just run the following command, replacing &lt;yourfile&gt; with the name of your Scala file:</p><pre>scalac -Xprint:all &lt;yourfile&gt;.scala</pre><p>Running this command on the above test program, we obtain the ASTs at each compilation phase. We compare the ASTs of the first phase (parser) and the last (terminal):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6cWSYOFDjlasNa-DiLpbKA.png" /><figcaption>AST after Phase 1 (Parser)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgCxI045DPrmGHzysdaRKQ.png" /><figcaption>AST of Phases 22–24(Delambdafy, JVM, Terminal)</figcaption></figure><p>As we can see, the AST has evolved dramatically from beginning to end of compilation. We also see that there are phases where the AST remained unchanged.</p><p>Although it is large, it is also now in a form that can be easily translated into a portable JVM bytecode structure. In Kotlin compilers, this is done using <strong>ASM</strong>: An all purpose Java bytecode manipulation and analysis framework. For more information on the ASM framework, check out <a href="https://asm.ow2.io/">the official documentation</a>.</p><p>Finally, after your program finishes compiling, the corresponding JVM bytecode of your classes should automatically be generated in the current working directory. If not, you can specify the option <strong>-Ydump-classes DIR</strong>, where <strong>DIR</strong> is a specified directory, to create these files after compilation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*iAOyJvP7bTLjurI9uAQOiQ.png" /></figure><h3>Scala’s Intermediate Representations</h3><p>An <strong>intermediate representation </strong>of a programming language is the data structures or code used by a compiler or virtual machine to represent source code.</p><p>In the case of Scala, intermediate representations include platform-independent <strong>JVM Bytecode</strong>, and platform-dependent <strong>Machine Code</strong>.</p><h4>JVM Bytecode</h4><p>In high-level programming, understanding JVM bytecode can help a Java programmer in a way similar to how understanding assembly might help a C/C++ programmer.</p><p>JDK8 comes with <strong>javap</strong>, a tool that lets us disassemble JVM bytecode within <strong>.class</strong> files. We will use javap to inspect the JVM bytecode generated from the previous example.</p><p>In the terminal, we type in the following command:</p><pre>javap -c MyProgram.class</pre><p>Where MyProgram.class is the JVM bytecode generated by scala. This returns the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*aGxK-LTm3PmZu17FLBiLbw.png" /></figure><p>Fortunately, it is not necessary to understand JVM bytecode to understand your Scala programs. However, it is an undeniable advantage to understand what is happening at a much lower level, especially in terms of performance. For more information on JVM bytecode, check out the official <a href="https://docs.oracle.com/javase/specs/">Java Virtual Machine Specification</a>.</p><h3>Internal Functions of JVM in Scala</h3><p>Scala being a functional programming language working on the JVM raises a question on how the functions are implemented since, JVM does not support functional programming natively. In these section we will see how JVM implements the Scala functions which would come in very handy while dealing with obscure bugs.</p><h4>Decompiling Functions</h4><p>If we look at a normal function which converts a number to its square:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*AxTTd7UZHUpeqAD9-kyzaQ.png" /></figure><p>If this code is decompiled, it would translate as:</p><pre>public static scala.Function1&lt;java.lang.Object, java.lang.Object&gt; square();<br>  Code:<br>    0: getstatic // Field RunExample$.MODULE$:LRunExample$;<br>    3: invokevirtual // Method RunExample$.square:()Lscala/Function1;<br>    6: areturn</pre><p>This translation is the conversion of the original code into an instance of Function1 trait of Scala. This trait extends the root class of all reference types- AnyRef class. With this example, we can conclude that every function in Scala are objects in some forms. For this case, it was the instance of FunctionN trait.</p><p>Let’s consider a test class with a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*t5zeDF3NUh-gYM5uUsWndQ.png" /></figure><p>On compilation, this will generate 2 files: <strong>Run.class </strong>and <strong>Run$$anonfun$1.class</strong>.</p><p>The <strong>Run$$anonfun$1.class</strong> is the function class. If we decompile it we get:</p><pre>public final class Run$$anonfun$1 extends scala.runtime.AbstractFunction1$mcII$sp implements scala.Serializable {<br>  public static final long serialVersionUID;<br>  public final int apply(int);<br>  public int apply$mcII$sp(int);<br>  public final java.lang.Object apply(java.lang.Object);<br>  public Run$$anonfun$1(Run);<br>}</pre><p>JVM basically just provides features like serializable, apply and constructor.</p><h4>The FunctionN Trait</h4><p>In the previous section, we saw the example involving trait Function1. In Scala, there are traits from Function1 to Function22. But then how do the developers put in 22 classes?</p><p>The answer is they don’t have to. The top of the source code always mentions as a comment:</p><pre>// GENERATED CODE: DO NOT EDIT. See scala.Function0 for timestamp.</pre><p>This proves that this is generated from somewhere and is not hand-coded at all. This trait in Scala is similar to the generic of Java language which handles the heterogeneous types.</p><p>Now, what if a function requires more than 22 parameters? This is a valid question. But in reality, 22 limit is really hard to reach. Even if this scenario occurs, it could be overcome by using nested tuples or other structures like HList.</p><p>It should be kept in mind though that the internal implementation of a function can change anytime but the core concept of a function being an object won’t change.</p><h4>Functions vs Methods</h4><p>Functions and methods share most of the keywords and the syntax but they are not same. The basic difference being that methods cannot be defined as values and can’t be passed around to other function as values. Methods are a part of Object Oriented Programming and are very different from functions which can be seen if we observe the byte code generated.</p><h4>Interoperability with Object Oriented Programming</h4><p>As we discussed above, in Scala, each function is considered an object which makes it easy to work with imperative or object oriented code. For instance, if we consider our square function from before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*k06ssEFscraL0Sg6" /></figure><p>This function takes an integer as parameter and returns an integer. It can also be consumed like a regular method. To a programmer it looks like a method while it actually is a function if consider behind the scene operations.</p><h3>From JVM Bytecode to Machine Code</h3><p>Finally, after all bytecode is generated for your Scala program, all that is left is for the <strong>Just-In-Time</strong> (<strong>JIT</strong>) <strong>compiler </strong>to translate the bytecode into machine code, which is then fed into memory for execution. The JIT compiler is one of the many functional components of the JVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmQJdz_qbpQUt7YOCJudwg.png" /></figure><p>As the name implies, the JIT compiler runs on demand, but only compiles machine code once. Since the JIT compiler is smart enough to recognize when code is already compiled, applications tend to run faster and faster as they run over time. This also means that code blocks which do not often run recieve less optimization.</p><p>An important thing to note is that the bytecode generation is the same among all platforms, however the machine code generation is not; this is an important recipe in optimizing not just Scala code execution, but other languages using JVM and JIT compiler such as Java and Groovy.</p><h3>Authors</h3><p>Alessandro Heres — <a href="https://github.com/alexheres">Github</a><br>Tristen Sprainis — <a href="https://github.com/Tsprainis">Github</a><br>Ayushi Priyadarshi — <a href="https://github.com/ayupriya">Github</a> | <a href="https://www.linkedin.com/in/ayushi-priyadarshi-21b237145">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=483e654bb6d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala: Debugging and Unit Testing]]></title>
            <link>https://medium.com/@alessandroheres/scala-debugging-and-unit-testing-3d357e71ccc?source=rss-6ae42849bfe4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d357e71ccc</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Alex Heres]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 05:29:09 GMT</pubDate>
            <atom:updated>2019-03-20T06:15:35.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ki0rq-MjVdBcLMjLRXb6Mg.jpeg" /></figure><p>Debugging is an essential skill in any programmer’s toolkit. In general, it is the process of locating and removing errors or bugs within a program. Thankfully, there are a variety of tools that simplify the debugging process to make the programmer’s job more efficient.</p><p>In the case of Scala, other than your standard stack trace and print statements, there is not much flexibility in terms of debugging programs when using a command line interface. Instead, the real power of debugging in Scala comes from external software, including Scala-supported IDEs, APIs, and libraries.</p><p>In this guide, we will focus on debugging Scala programs using the IntelliJ IDE, a method of debugging that has become increasingly popular and well-documented. In case you need to help installing the IntelliJ IDE, or need to know the necessary steps to set up a Scala project in IntelliJ, we recommend you take a look at our <a href="https://medium.com/@alessandroheres/scala-programming-an-introduction-33464b390d57">installation guide</a>. Note that we are using sbt to build our Scala projects.</p><h3>Introduction to Debugging in IntelliJ</h3><p>With the IntelliJ IDE, we have the option of debugging by using either IntelliJ IDEA or the sbt shell, though they are both similar in function and results. We will mostly focus on the debugging process using IntelliJ IDEA.</p><h4>Breakpoint Debugging and the Debug Pane</h4><p><strong>Breakpoints </strong>allow a programmer to examine a program at a specific point during its execution, down to a specific line of code. With the IntelliJ IDE, the programmer specifies breakpoints by placing a ‘marker’ on a specific line of code. After specifying the breakpoints (there can be none to many), the program is executed in debug mode, and will then suspend further operations once it reaches a breakpoint.</p><p>It is very easy to insert and remove breakpoints in your program: in the left gutter of the editor, simply click any line(s) of code, just to the right of the line number. If no breakpoint exists on a line, clicking it will create a new one. If a breakpoint already exists on a line, then clicking it will remove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*pbO0_LWARKGo5BspsWLvGQ.png" /></figure><p>Note that you can add as many breakpoints to your liking. You can add or remove breakpoints before or during program execution, but NOT during the debug building process.</p><p>To get our program to actually “pause” at a breakpoint, we must run it in debug mode. You can do so by clicking the <strong>spider icon </strong>near the top right of the IDE, or from the menu bar choose <strong>Run &gt; Debug ‘MyProgram’</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*IDjtY8p9sdXFWROh5Y3DNw.png" /></figure><p>After selecting the debug option and compilation finishes, the <strong>Debug Pane </strong>should automatically appear at the bottom of the IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*kFP8oCkiTZ8PJ0OnxHEpWw.png" /></figure><p>The Debug Pane contains a variety of useful information and tools we will cover in this guide, starting with the stepping toolbar located at the top of the Debug Pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*7y1m4ouyxqDNr5Gp-7G1-A.png" /></figure><p>The following are short descriptions of how each option functions. From left to right:</p><ol><li><strong>Show Execution Point — </strong>Shows the current program execution point.</li><li><strong>Step Over — </strong>Steps to the next line in the current file.</li><li><strong>Step Into — </strong>Steps to the next line to be executed.</li><li><strong>Force Step Into — </strong>Same as <strong>Step Into</strong>, but ignores stepping filters for libraries, constructors, etc.</li><li><strong>Step Out — </strong>While in a method, steps to the first line executed after returning from the method.</li><li><strong>Drop Frame — </strong>Moves execution point back to the method call dropping current frames from the stack.</li><li><strong>Run to Cursor — </strong>Runs program until the line where the caret is located.</li><li><strong>Evaluate Expression — </strong>Used to evaluate arbitrary expressions, usually those encountered during a program’s execution.</li></ol><h4>The Frames Pane and Variables Pane</h4><p>The <strong>Frames Pane </strong>allows you to examine all the threads of your Scala application, and even allows you to customize how your application is threaded. Simply select a thread from the drop-down menu to examine it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*y52xBD80DKLLVCxWbDg4UQ.png" /></figure><p>Examining a thread allows you to view the stack frame, examine frames and their stored values, navigate between frames, and jump to a frame’s source code.</p><p>The <strong>Variables Pane </strong>displays all active variables of the current stack frame. Selecting a particular stack frame from the Frames Pane allows you to view all the active variables in that scope, as well as their stored values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*C6m5OGNLVZZucE5zqdwT0g.png" /></figure><h4>Breakpoint Types</h4><p>Depending on the kind of code a line contains, the <strong>type </strong>of breakpoint may differ.</p><ul><li><strong>Line Breakpoints </strong>are set on executable lines of code, including simple expressions and lambda expressions.</li><li><strong>Method Breakpoints </strong>are placed at method declarations, and trigger when entering or exiting a method. This allows you to check conditions related to method entry and exit.</li><li><strong>Exception Breakpoints </strong>trigger when a specific exception is thrown. Setting an exception breakpoint requires more than a left-click on a line to set. From the menu bar, navigate to <strong>Run &gt; View Breakpoints</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*8e-5gkvzNjTaKa83iNBZbQ.png" /></figure><p>In the resulting Breakpoints window, click the <strong>+ </strong>above the left pane, and select <strong>Java Exception Breakpoints</strong>. (Note: to remove an exception breakpoint, select it and click <strong>-</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*K_d6_1AE06aG5Mqa-qKWyA.png" /></figure><p>In the resulting Enter Exception Class window, you can search for the exception you desire. Among exceptions specific to Scala, you can also find a plethora of Java-supported exceptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*XPdK_gdIoZZusjO2O8PWvw.png" /></figure><p>Select your desired exception and click <strong>OK</strong>. The exception should be added automatically to your list of exception breakpoints, and well as be enabled by default.</p><h4>Breakpoint Properties</h4><p>You can configure various properties of a breakpoint, depending on its type. Editing these properties is as easy as right-clicking a breakpoint. To see the list of all configurations, right-click any breakpoint, and then choose the <strong>more </strong>option at the bottom of the resulting window to open the <strong>Breakpoints </strong>window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*HPuphCk6jh8slJq6kx-E1w.png" /></figure><p>In the Breakpoints window, we can immediately see that there are a handful of options to customize our breakpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*ypYfXLIvDE59_-OApgufOQ.png" /></figure><p>Here are just a few of these options and their function:</p><ul><li><strong>Condition — </strong>Activates a breakpoint if a specified condition is met. For example, in a For Loop, you could get a breakpoint to activate on a specific loop.</li><li><strong>Log:<br>“Breakpoint hit” message — </strong>Logs a message to the console upon hitting a breakpoint.<br><strong>Stack Trace — </strong>Logs a breakpoint’s stack trace upon being hit.</li><li><strong>Evaluate and Log — </strong>Evaluates an expression and logs the result to console.</li><li><strong>Disable until breakpoint is hit — </strong>Current breakpoint will remain disabled until another specified breakpoint is hit, triggering the current one.</li><li><strong>Instance Filters — </strong>limit breakpoint hits with particular object instances.</li><li><strong>Class Filters — </strong>Filters out classes where exceptions will be caught.</li><li><strong>Pass Count — </strong>Triggers a breakpoint only after being hit a specified number of times.</li><li><strong>Caller Filters — </strong>Use to trigger a breakpoint after being called (or NOT called) from a particular method.</li></ul><p>These are only some of the options, and more might be available depending on the type of breakpoint being configured. For more information on breakpoints, check out the <a href="https://www.jetbrains.com/help/idea/using-breakpoints.html">official documentation on JetBrains</a>.</p><h4>Watches</h4><p>A <strong>watch </strong>can be created for variables or expressions to spectate their evaluation throughout the context of a particular frame. By default, watches are viewed through the Variables Pane (denoted by the <strong>glasses </strong>icon), though you can separate watches into their own pane, the <strong>Watches Pane</strong>, by clicking the glasses icon in the Variables Pane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*xIpXC7udf5gqSVgqxtLIdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*krG0U1AEjUZI_MN65zGNzg.png" /></figure><p>Whichever pane you choose to display your watches in, the process of adding and removing them are the same. Note that you can only add and remove watches during a debugging session. Click the <strong>+ </strong>to add a watch, or the <strong>-</strong>to delete a watch. You can also perform these actions through the right-click menu.</p><p>To edit a watch and the expression it represents, right-click it and select <strong>edit</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*hgPet5c1Q6LLy3I7ErFazA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*mjmvV-PYYSfWPy6hxHVcRw.png" /></figure><p>As your program runs and variables are declared, corresponding watches are automatically added by default, and are displayed only while the program is executing in their respective stack frame. Manually creating a watch allows you to track the evaluation of expressions outside of that scope. This tracking persists even throughout various debugging sessions!</p><h3>Exploring Scala Debugging: A YouTube Video</h3><p>Here is a quick-start guide on how to debug a Scala program using IntelliJ IDEA. We learn how to apply the previously mentioned debugging concepts within the IntelliJ environment.</p><p><a href="https://www.youtube.com/watch?v=Fe3yB1pHq8w">https://www.youtube.com/watch?v=Fe3yB1pHq8w</a></p><h3>ScalaTest: A Unit Testing Framework</h3><p>There are a few Unit Testing Frameworks for Scala, such as ScalaTest, Specs2, and uTest. In this guide, we will be focusing on <strong>ScalaTest</strong>, which is considered by many to be the most popular and well-documented Unit Testing Framework available.</p><p>Fortunately, ScalaTest already comes with the Scala plugin for IntelliJ, so all we need is to include the library dependencies. When building a Scala project with sbt, we must add the following lines of code to our project’s <strong>build.sbt </strong>file:</p><pre>libraryDependencies += ”org.scalactic”%%”scalactic”%”3.0.1&quot;<br>libraryDependencies += “org.scalatest”%%“scalatest”%“3.0.1”%“test”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*FXqfmnEtr7YKPLGiEh2YvQ.png" /></figure><p>After adding the dependencies, IntelliJ will notify you that you MUST update your sbt project. Choose to either <strong>Import Changes </strong>or <strong>Enable Auto-Import</strong>.</p><p>The dependencies that we added to build.sbt file in the above will give us access to the functions like FunSuite and test(). The test function allows us to collect results from the assert statements in the function body.</p><h4>Getting Started with ScalaTest</h4><p>Let’s create a simple scala program to calculate the square of a number and perform a unit testing on it.</p><h4>Creating a Program:</h4><ol><li>On the left panel, go to <strong>src&gt; main&gt; scala</strong>.</li><li>Right click on the scala folder and go to <strong>New&gt; Scala Class</strong></li><li>A dialogue box will appear on the screen. Enter the name CalSquare and choose the kind <strong>Object</strong>.</li><li>IntelliJ will create an outline for the program. Add the following code to the outline.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*MPDQ7uXJjC0AfocJL7xwPQ.png" /></figure><h4>Creating a Test:</h4><ol><li>In the project panel on the left, go to <strong>test&gt;scala</strong>.</li><li>Right click on the scala folder and go to <strong>New&gt; Scala Class</strong>.</li><li>A dialogue box will appear on the screen. Enter the name CalSquareTest and click <strong>OK</strong>.</li><li>Add the following code to CalSquareTest.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*uUx8waNHsug8v3GUxtZSFw.png" /></figure><p>In the source code, right-click CalSquareTest and select <strong>Run</strong> CalSquareTest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2T111U-GF3KX52E6KyD67w.png" /></figure><p>The above image shows that the Unit test passed successfully. If needed, we can add more tests cases by adding more assert statements in the code.</p><p>Our example shows only one of the many way to perform tests; ScalaTest supports more than just the test() and assert() functions, and has multiple styles other than just FunSuite. For more information on the usage of ScalaTest or its functionalities, check out the <a href="http://www.scalatest.org/user_guide">user guide</a> and <a href="http://www.scalatest.org/scaladoc">documentation</a> on the official website.</p><h3>Authors</h3><p>Alessandro Heres — <a href="https://github.com/alexheres">Github</a><br>Tristen Sprainis — <a href="https://github.com/Tsprainis">Github</a><br>Ayushi Priyadarshi — <a href="https://github.com/ayupriya">Github</a> | <a href="https://www.linkedin.com/in/ayushi-priyadarshi-21b237145">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d357e71ccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Coding Conventions: An Introduction]]></title>
            <link>https://medium.com/@alessandroheres/scala-coding-conventions-an-introduction-73aaf5b73659?source=rss-6ae42849bfe4------2</link>
            <guid isPermaLink="false">https://medium.com/p/73aaf5b73659</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Alex Heres]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 06:41:29 GMT</pubDate>
            <atom:updated>2019-02-25T06:41:29.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtOyg7rBOnuPU0tehyNt7w.jpeg" /></figure><p>Picking up a new programming language can be tricky, this guide aims to simplify that for those looking to learn Scala. We will introduce and go over the main ideas one should know to program in Scala, including expressions, data types, as well as abstraction of data and control.</p><h3><em>Introduction to Expressions</em></h3><h4>Expressions, Values, and Variables</h4><p>Simply put,<strong> Expressions</strong> are computable statements, such as adding two values or string concatenation, and a <strong>Value</strong> is the result of an expression. Using the val keyword, The following Scala code stores a computed value and prints it.</p><pre>val x = 1 + 1 // implicit declaration<br>println(x)</pre><pre>val y: Int = 1 + 1 // explicit declaration</pre><p>Here, the value type of <strong>x</strong> is inferred, but you can also explicitly declare the value type, as it was for <strong>y</strong>. Note the necessary <strong>: </strong>after the value name and before the type name.</p><p>Note that <strong>values</strong> CANNOT be re-assigned, meaning they are constant. If re-assigning is needed, then one should instead declare a <strong>variable</strong> with the keyword var. You can choose to explicitly state the type of variable or not, just like values.</p><pre>var x: Int = 1 + 1<br>x = 3 // will compile</pre><p>Finally, brackets {} can be used to combine expressions into <strong>blocks</strong>. Note that in a code block, the expression in the block is the returned value.</p><pre>println({<br>  val x = 1 + 1<br>  x + 1<br>}) // prints 3</pre><h4>Functions and Methods</h4><p><strong>Functions </strong>are expressions that take parameters. In Scala, they can be declared either anonymously or be given a name.</p><pre>(x: Int) =&gt; x + 2  // anonymous<br>val addTwo = (x: Int) =&gt; x + 2  // named</pre><p>Observe the syntax: The <strong>=&gt;</strong> operator here creates a function instance. To the left of the <strong>=&gt;</strong> are the function parameters, and to the right is the involved expression. Functions can have many parameters or none at all. Functions can also be a part of another function’s expression.</p><pre>val add = (x: Int, y: Int) =&gt; x + y<br>println(add(1, 2)) // 3<br><br>val getAdd = () =&gt; add(3, 4)<br>println(getAdd()) // 7</pre><p><strong>Methods</strong> are similar to functions, with some minor differences. Firstly, they must be defined with the <strong>def</strong> keyword. Secondly, methods can have multiple parameter lists (or none at all). Finally, a return type must be specified after the parameter list(s), denoted by a <strong>: </strong>followed by the return type and value.</p><pre>def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = {<br>  (x + y) * multiplier<br>}<br>println(addThenMultiply(1, 2)(3)) // 9</pre><h4>Multiple Parameter Lists and Currying</h4><p><strong>Currying</strong> is a technique used in Scala that transforms a function with multiple arguments into a function with only one argument. This single argument is the first value of the original function. The function then returns another single argument function. This function then has access to the first value that was returned and has a function that takes a single argument, which would be the second value of the original function. This chaining would continue on for as many arguments as the original function had. The last function in the chain would have access to all to the arguments from earlier in the chain and could do whatever was necessary of the original function.</p><p>In Scala, there is a shorthand way of currying and the standard way of currying. The shorthand for currying is just separating the arguments. The long way of currying involves a slightly different approach.</p><pre>def multiply(multiplier1: Int): (Int =&gt; Int) = {<br>  (multiplier2: Int) =&gt; {<br>    multiplier1 * multiplier2<br>  }<br>}</pre><pre>// store multiply function, where multiplier1 = 3<br>val multiplyBy = multiply(3) <br>// call stored function, finish calculation with multiplier2 = 4<br>val resultMultipliedBy4 = multiplyBy(4) // = 12</pre><p>This is an example of the longhand version of currying. The following is a shorthand version of the same code that allows you to list one argument after the other. Note the (_) when we initially store the multiply function.</p><pre>def multiply(multiplier1: Int)(multiplier2: Int): Int = {<br>  multiplier1 * multiplier2<br>}</pre><pre>val multiplyBy = multiply(3)(_)<br>val resultMultipliedBy = multiplyBy(4) // 12</pre><h3>Data Types</h3><p>All values in Scala have a data type, functions included. The following diagram from the official documentation illustrates the data type hierarchy of the Scala language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vBk1sEV1xl6QZoE7-fDpxA.jpeg" /><figcaption>Source: <a href="https://docs.scala-lang.org/tour/unified-types.html">https://docs.scala-lang.org/tour/unified-types.html</a></figcaption></figure><p>Here are some of the most important things to take away from this diagram:</p><ul><li>The <strong>Any</strong> type is the supertype of all types, and has two direct subclasses <strong>AnyVal</strong> and <strong>AnyRef</strong>.</li><li>The <strong>AnyVal</strong> type represents value types, which includes <strong>Double</strong>, <strong>Float</strong>, <strong>Long</strong>, <strong>Int</strong>, <strong>Short</strong>, <strong>Byte</strong>, <strong>Unit</strong>, <strong>Boolean</strong>, and <strong>Char</strong>. while <strong>AnyRef</strong> represents reference types.</li><li><strong>Unit</strong> is a type that carries no meaningful information. It is similar to the <strong>void</strong> type from the C languages.</li><li>The <strong>AnyRef </strong>type represents reference types, and includes all user-defined types.</li><li><strong>Nothing</strong> is the subtype of all types, and does not evaluate to a value. Common use of the <strong>Nothing</strong> type is to signal non-termination in code.</li><li><strong>Null </strong>is the subtype of all reference types, and is invoked with the keyword <strong>null</strong>.</li></ul><h4>Type Casting</h4><p>The following diagram represents Scala’s type casting rules. If type A points to type B, then type A can be cast into type B. However, the inverse is NOT true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AQ4luN7U59eNVMxZfeBVQQ.jpeg" /><figcaption>Source: <a href="https://docs.scala-lang.org/tour/unified-types.html">https://docs.scala-lang.org/tour/unified-types.html</a></figcaption></figure><p>Here is a simple example that illustrates this typecasting hierarchy.</p><pre>var x: Int = 50000<br>var y: Long = x  // will compile, Int cast into Long<br>var z: Short = x  // will NOT compile, Int cast into Short</pre><p>The same logic applies when performing arithmetic on two numbers of different types. Scala will make the resulting variable of the ‘upper’ type. For example, adding an Integer and a Short must result in an integer. Multiplying a Short and a Long results in a Long, and so forth.</p><p>Even though casting is one-way, Scala has various functions that allows us to cast backwards. However this should always be done carefully as to avoid type mismatching, loss in precision, or overflow and underflow. Here are a couple of examples:</p><pre>var myInt: Int = 100000<br>var myShort: Short = 5<br>println(myInt) // 100000<br>println(myInt.toShort) // -31072, overflow occurs<br><br>var result1: Int = myShort + myInt // will compile, 100005<br>var result2: Short = myShort + myInt.toShort // ERROR, Int expected</pre><h3>Abstraction in Scala</h3><p>In general, there are two main kinds of abstraction in computer science; <strong>Data Abstraction</strong> and <strong>Control Abstraction</strong>. These concepts are used in programming practices to improve program efficiency and readability.</p><h3>Data Abstraction</h3><p>In general, <strong>Data Abstraction </strong>refers to hiding details of data, leaving only the essential details to make the data easier to work with and comprehend. We now go over some structures in Scala related to this idea of abstraction.</p><h4>Classes</h4><p><strong>Classes </strong>are defined with the <strong>class</strong> keyword, followed by its name and its construction parameters. You can then create an instance of a defined class with the <strong>new</strong> keyword.</p><pre>class Student(name: String, age: Int) {<br>  def summary(major: String): Unit =<br>    println(name + &quot;, &quot; + age.toString + &quot;, &quot; + major)<br>}<br><br>val testStudent = new Student(&quot;John Doe&quot;, 21)<br>testStudent.summary(&quot;CompSci&quot;) // John Doe, 21, CompSci</pre><p>Scala also has <strong>Case Classes</strong>. Unlike ordinary classes, case classes by default are immutable and compared by value. Case classes also do not require the <strong>new </strong>keyword for instantiation.</p><pre>case class Name(first: String, last: String)<br><br>val personA = Name(&quot;John&quot;,&quot;Doe&quot;)<br>val personB = Name(&quot;John&quot;,&quot;Doe&quot;)<br>val personC = Name(&quot;Susan&quot;,&quot;Blanco&quot;)<br><br>val compareNames = (x: Name, y: Name) =&gt; x == y<br>compareNames(personA, personB)  // true<br>compareNames(personA, personC)  // false</pre><h4>Objects</h4><p><strong>Objects </strong>are defined with the <strong>object </strong>keyword. Objects are essentially singleton classes, and can be accessed by their name.</p><pre>object InstanceTest {<br>  private var counter = 0<br>  def addOne(): Int = {<br>    counter += 1<br>    counter<br>  }<br>}<br>​<br>val firstInst: Int = InstanceTest.addOne()<br>val secondInst: Int = InstanceTest.addOne()<br>​<br>println(firstInst) // 1<br>println(secondInst) // 2</pre><h4>Abstract Types: Traits and Abstract Classes</h4><p><strong>Traits</strong> are used to share interfaces and fields between classes. They have no construction parameters and cannot be instantiated. Instead, traits are inherited by classes and objects using the <strong>extends</strong> keyword. You can also implement a trait’s abstract members by with the <strong>override</strong> keyword.</p><pre>trait printer {<br>  def echo() {<br>    println(&quot;Testing echo method.&quot;)<br>  }<br>}<br>​<br>class printClass(message: String) extends printer {<br>  override def echo() {<br>    println(message)<br>  }<br>}<br>​<br>var test = new printClass(&quot;Hello World!&quot;)<br>test.echo()  // prints &quot;Hello World&quot;</pre><p><strong>Abstract Classes </strong>are similar to traits, with some minor differences. Firstly, Abstract Classes can have construction parameters and type parameters, while traits can only have type parameters. Secondly, a class can inherit many traits, but only one abstract class. Scala class abstraction mechanism is very similar to the Java abstraction mechanism. A class in Scala can extend only one abstract class and does not support multi-inheritance. A class can have abstract as well as non-abstract methods in Scala.</p><p>Abstract methods are methods which do not have any body. In other words, they do not contain an implementation.</p><pre>// Abstract class<br>abstract class author {<br>  // abstract method<br>  def details()<br>}</pre><pre>// Book class extends abstract class<br>class Book extends author {<br>  def details() {<br>    println(&quot;Author name:Joe&quot;)<br>    println(&quot;Topic name: Abstract class in Scala&quot;)<br>  }<br>}</pre><pre>object Main {<br>// Main method<br>  def main(args: Array[String]) {<br>    // objects of Book class<br>    var obj = new Book()<br>    obj.details()<br>  }<br>}</pre><p>In Scala, we cannot instantiate objects of an abstract class, otherwise the compiler will give an error. These abstract classes also contains fields. These fields can be accessed by the methods of abstract class or the methods of classes implementing the abstract class. Like Java, Scala abstract classes also have constructors which are called when an instance of the class that inherits the abstract class is created. An abstract class in Scala can contain <strong>final</strong> methods to avoid being overridden.</p><h4>Variances</h4><p>From the <a href="https://docs.scala-lang.org/tour/variances.html">official Scala Documentation</a>, <strong>variance </strong>is defined as follows:</p><blockquote>“Variance is the correlation of subtyping relationships of complex types and the subtyping relationships of their component types.”</blockquote><p>In Scala, variance is applied to type parameters of generic classes to help clarify and refine the relationships between classes. There are three types of variance: Covariance, Contravariance, and Invariance.</p><p>A <strong>covariant </strong>class consists of a type parameter A which can be denoted as +A. This implies that for a covariant class List[+A], two type parameters A and B where A is a subtype of B then, List[A] is a subtype of List[B].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*OBp_NMTHoF88ONnJytXvjw.png" /></figure><p>In the above example, List[Cat] is a List[Animal] and List[Dog] is a List[Animal] because of the covariant parameter. Because of that, printAnimalNames(cats) and printAnimalNames(dogs) are compiled without error.</p><p>A <strong>contravariant </strong>class can be represented as some class with a parameter type A denoted as -A. That is, for some class Writer[-A], the type parameters A and B where A is a subtype of B then Writer[B] is subtype of Writer[A]. This parameter and class relationship is the opposite of that in covariance, and also opposite with respect to the subtyping relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*-txmSSjcYOr2tGPHPMLjyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*MsnDxYRLvCtcMBfnao6sIw.png" /></figure><p>In the above example, the output of both printMyCat(catPrinter) and printMyCat(animalPrinter) will be same — Boots. This is because a printer[Animal] can print any animal and hence can print any cat. The inverse, however, is not true.</p><p>The classes in Scala are <strong>invariant </strong>by default, meaning these classes do not have covariance or contravariance properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*99xKKxC3zLJ_ei6L4VYW-w.png" /></figure><p>In the above example, a Container[Cat] is not a type of Container[Animal] and vice-versa. It may seem like a covariant class but making this mutable generic class a covariant would not be safe.</p><h4>Inheritance in Scala</h4><p>Scala supports many different types of inheritance. We will go over each kind using simple examples.</p><p>First is <strong>single inheritance</strong>. Suppose we have the following two classes, <strong>Grandparent</strong> and <strong>Parent.</strong> By making Parent inherit from Grandparent, we demonstrate single inheritance. For example:</p><pre>class Grandparent {<br>  var FirstName: String = &quot;Julius&quot;<br>  var SecondName: String = &quot;Caesar&quot;<br>}<br><br>class Parent extends Grandparent { <br>  var Age: Int = 40<br>}</pre><p>Recall that the <strong>extends</strong> keyword implements inheritance. Using the code above, we can create a new Parent object and call the either the FirstName or SecondName variable inherited from the Grandparent class.</p><pre>var single = new Parent()<br>println(&quot;Name: &quot; + single.FirstName) // &quot;Julius&quot;<br>println(&quot;Age: &quot; + single.Age.toString) // &quot;40&quot;</pre><p>Continuing from our previous example, we can have <strong>multilevel inheritance </strong>if we create another class that inherits the Parent class. For example, we create the <strong>Child1 </strong>class:</p><pre>class Child1 extends Parent { <br>  var FavoriteFood: String = &quot;Pizza&quot;<br>  <br>  def details() { <br>    println(&quot;Name: &quot; + FirstName)<br>    println(&quot;Age: &quot; + Age.toString)<br>    println(&quot;Favorite Food: &quot; + FavoriteFood)<br>  } <br>} <br><br>var multilevel = new Child1()<br>multilevel.details() // Julius, 40, Pizza</pre><p>Now the class hierarchy is as follows: Child1 inherits Parent inherits Grandparent.</p><p><strong>Hierarchical Inheritance</strong> is when one class has multiple subclasses. Adding even further to our example, we can create a <strong>Child2</strong> class that also inherits from Parent. At this point, the Parent class now acts as the base class for both the Child1 and Child2 classes; a form of hierarchical inheritance.</p><pre>class Child2 extends Parent { <br>  var FavoriteFood: String = &quot;Ice Cream&quot;<br>  <br>  def details() { <br>    println(&quot;Name: &quot; + SecondName)<br>    println(&quot;Age: &quot; + Age.toString)<br>    println(&quot;Favorite Food: &quot; + FavoriteFood)<br>  } <br>} <br><br>var hierarchical = new Child2()<br>hierarchical.details() // Caesar, 40, Ice Cream</pre><p>Multiple inheritance is the opposite of hierarchical influence; that is, when one class inherits from multiple base classes. However, recall that Scala does not allow a class to inherit from more than one base class. Instead we must inherit multiple traits, which Scala does allow. Note this example is different from the previous ones.</p><pre>trait First { def FirstMethod() } <br>trait Second { def SecondMethod() } <br>trait Third { def ThirdMethod() }<br><br>class Multiple extends First with Second with Third {       <br>  <br>  def FirstMethod() { println(&quot;First Trait&quot;) }<br>      <br>  def SecondMethod() { println(&quot;Second Trait&quot;) }<br>  <br>  def ThirdMethod() { println(&quot;Third Trait&quot;) }<br>} <br><br>var multi = new Multiple()<br>multi.FirstMethod() // &quot;First Trait&quot;<br>multi.SecondMethod() // &quot;Second Trait&quot;<br>multi.ThirdMethod() // &quot;Third Trait&quot;</pre><p>Here we create three traits First, Second, and Third. and a class Multiple<strong> </strong>that inherits all three traits. To extend more than one trait, we use the <strong>with </strong>keyword after extending the first trait. In Scala, traits that compose a class are known as <strong>mixins</strong>.</p><p>Finally,<strong> Hybrid Inheritance </strong>is a combination of two or more of the previously listed types of inheritance.</p><h3>Control Abstraction</h3><p><strong>Control Abstraction </strong>means to hide complex execution flows of a program behind a simplified representation. Such examples are for loops and while loops found in C and Java languages.</p><h4>If-Else Statements</h4><p><strong>If-Else statements</strong> work the same way in Scala as most other languages. There is a boolean statement in the if section. “If” this statement is true, it expression in the if portion is executed. “Else” the statement is false, it executes the else section. Else and else if sections are optional. Else if sections are after the initial if, and before a final else.</p><pre>def ifTest(x: int) {<br>  if(x &lt; 10) {<br>    println(&quot;This is the if&quot;)<br>  } else if(x &gt; 10 &amp; x &lt; 15) {<br>    println(&quot;This is the else if&quot;)<br>  } else {<br>    println(&quot;This is the else&quot;)<br>  }<br>}</pre><p>There are three main rules to keep in mind when constructing these statements:</p><ol><li>If-Else statements can have zero or one else, and must come after any else if’s.</li><li>If-Else statements can have zero to many else if’s, and must come before the else (if any).</li><li>Once an if or else if succeeds, no other else if’s or else that follow are tested.</li></ol><h4>While Loops</h4><p><strong>While loops</strong> are loops that will continue to be executed until a condition is met and the loop is terminated. It works the same way in Scala as it does in many other languages.</p><pre>var x = 0<br>while(x &lt; 10) {<br>  println(&quot;This is in the while loop”)<br>  x = x + 1<br>} // prints 10 times</pre><h4>Match-Case Expressions</h4><p><strong>Match </strong>expressions in Scala function similarly to the switch-case statements found in C++ and Java languages. The following example from the <a href="https://alvinalexander.com/scala/how-to-use-pattern-matching-scala-match-case-expressions">Scala Cookbook by Alvin Alexander</a> shows just how powerful match-case statements can be.</p><pre>def echoWhatYouGaveMe(x: Any): String = x match {<br><br>    // constant patterns<br>    case 0 =&gt; &quot;zero&quot;<br>    case true =&gt; &quot;true&quot;<br>    case &quot;hello&quot; =&gt; &quot;you said &#39;hello&#39;&quot;<br>    case Nil =&gt; &quot;an empty List&quot;<br><br>    // sequence patterns<br>    case List(0, _, _) =&gt; &quot;a three-element list with 0 as the first element&quot;<br>    case List(1, _*) =&gt; &quot;a list beginning with 1, having any number of elements&quot;<br>    case Vector(1, _*) =&gt; &quot;a vector starting with 1, having any number of elements&quot;<br><br>    // tuples<br>    case (a, b) =&gt; s&quot;got $a and $b&quot;<br>    case (a, b, c) =&gt; s&quot;got $a, $b, and $c&quot;<br><br>    // constructor patterns<br>    case Person(first, &quot;Alexander&quot;) =&gt; s&quot;found an Alexander, first name = $first&quot;<br>    case Dog(&quot;Suka&quot;) =&gt; &quot;found a dog named Suka&quot;<br><br>    // typed patterns<br>    case s: String =&gt; s&quot;you gave me this string: $s&quot;<br>    case i: Int =&gt; s&quot;thanks for the int: $i&quot;<br>    case f: Float =&gt; s&quot;thanks for the float: $f&quot;<br>    case a: Array[Int] =&gt; s&quot;an array of int: ${a.mkString(&quot;,&quot;)}&quot;<br>    case as: Array[String] =&gt; s&quot;an array of strings: ${as.mkString(&quot;,&quot;)}&quot;<br>    case d: Dog =&gt; s&quot;dog: ${d.name}&quot;<br>    case list: List[_] =&gt; s&quot;thanks for the List: $list&quot;<br>    case m: Map[_, _] =&gt; m.toString<br><br>    // the default wildcard pattern<br>    case _ =&gt; &quot;Unknown&quot;<br>}</pre><p>Observe that Match-case statements can match constant patterns, sequence patterns, case classes, and even typed patterns.</p><h4>Foreach Loops</h4><p>In Scala, the <strong>foreach </strong>method takes in a <em>procedure</em> (a function with result type Unit), and applies it to each element of a Scala List.</p><pre>var x: List[Int] = List(1, 2, 3)<br>x.foreach(println)</pre><h4>For Comprehension</h4><p>Unlike the <em>foreach</em> method, <strong>for comprehensions</strong>, or for-loops, are not restricted to lists. You can also refine the results of a for comprehension with an <strong>if</strong> conditional.</p><pre>val names = Vector(&quot;John&quot;, &quot;Bob&quot;, &quot;Susan&quot;, &quot;Billy&quot;)<br>for (x &lt;- names) println(x)  // John, Bob, Susan, Billy<br>for (y &lt;- names if y.startsWith(&quot;B&quot;)) println(y)  // Bob, Billy</pre><p>Note that in this example, <strong>x &lt;- names</strong> and <strong>y &lt;- names</strong> are generators, where x and y here can be named to your liking. For comprehensions can have multiple generators, such as in the following example:</p><pre>for (i &lt;- 1 to 2; j &lt;- 1 until 3 if i == j) {<br>  println(s&quot;i = $i, j = $j&quot;)<br>} // prints (i = 1, j = 1) and (i = 2, j = 2)</pre><p>Note that <strong>1 to 2 </strong>and <strong>1 until 3</strong> represent the same range; using the <strong>until</strong> keyword omits the upper bound. You can also traverse a range of values in multiples with the <strong>by</strong> keyword. For example, <strong>1 to 10 by 2 </strong>would traverse through values 1, 3, 5, 7, and 9.</p><h4>Map and Flatmap</h4><p>In Scala, the <strong>Map </strong>method is used when you want to apply a function to a Scala List. Unlike the <em>foreach</em> method, map actually returns a value. We can either define our function either outside or inside of the map method.</p><pre>var x = List(1, 2, 3)<br>def numToString (num: Int): String = {<br>  num.toString<br>}<br><br>var ans1 = x.map(numToString) // List[String] = {&quot;1&quot;,&quot;2&quot;,&quot;3&quot;}<br>var ans2 = x.map(y =&gt; y.toString) // same as above<br>ans1.foreach(println)  // We can iterate over our new Lists</pre><p><strong>flatMap</strong> is best explained by example. We will use the following method that takes an integer as input, and returns a List of two integers consisting of the original value and the other incremented by 5. We compare the differences in the values returned by the Map and Flatmap methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*inaC2DwT-azfreByr4dujA.png" /></figure><p>Notice that <strong>map</strong> returns a list of lists; one list for each element in numList. On the other hand, <strong>flatMap</strong> essentially <em>flattened </em>all of the resulting lists into one, giant list. Knowing this difference could prove beneficial if you prefer working with one List structure over the other.</p><h4>Filter, filterNot, and withFilter</h4><p><strong>Filter </strong>is a method used to filter items in a collection to create a new collection that contains only the elements that match your filter criteria. The <strong>filterNot</strong> method also creates a new filtered collection from an original, but the result contains the elements that do NOT match your filter criteria.</p><pre>val x = List.range(1, 10) // x = List(1, 2, 3, 4, 5, 6, 7, 8, 9)<br>val evens = x.filter(_ % 2 == 0) // evens = List(2, 4, 6, 8)<br>val odds = x.filterNot(_ % 2 == 0) //odds = List(1, 3, 5, 7, 9)</pre><p>In our example, the <strong>filter </strong>method includes only the multiples of two. On the other hand, the <strong>filterNot </strong>method excludes the filtered elements, such that it does NOT include multiples of two.</p><p><strong>withFilter</strong> performs the same evaluations that <strong>filter</strong> does to create a filtered collection but with one major difference: withFilter restricts the domain of subsequent map, flatmap, foreach, and withFilter operations. In other words, it performs ‘lazy’ filtering, whereas <strong>filter </strong>performs ‘eager’ filtering. This is more of an performance optimization than anything, but there are some cases where <strong>withFilter </strong>can lead to different output than <strong>filter</strong>. See <a href="https://alvinalexander.com/scala/examples-shows-differences-between-strict-lazy-evaluation-in-scala">this example</a> for more info.</p><h3>Authors</h3><p>Alessandro Heres — <a href="https://github.com/alexheres">Github</a><br>Tristen Sprainis — <a href="https://github.com/Tsprainis">Github</a><br>Ayushi Priyadarshi — <a href="https://github.com/ayupriya">Github</a> | <a href="https://www.linkedin.com/in/ayushi-priyadarshi-21b237145">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73aaf5b73659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Programming: An Introduction]]></title>
            <link>https://medium.com/@alessandroheres/scala-programming-an-introduction-33464b390d57?source=rss-6ae42849bfe4------2</link>
            <guid isPermaLink="false">https://medium.com/p/33464b390d57</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Alex Heres]]></dc:creator>
            <pubDate>Sun, 17 Feb 2019 22:06:59 GMT</pubDate>
            <atom:updated>2019-02-18T02:51:28.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpgoZL9OdEDu9DU8AhmG1w.jpeg" /></figure><p>Scala is a multi-paradigm programming language that runs on the Java Virtual Machine (JVM). In other words, it is a language that supports many different styles of coding, including object-oriented, imperative, and functional programming. The fact that it runs on JVM means that any executable Scala code is guaranteed to yield the same results on a variety of different platforms (A.K.A. portability), including Windows, MacOS, Linux, and Android, among many others.</p><p>In this guide, we will show how to get started writing Scala code for both Windows and Linux operating systems. We will also install a user-friendly Integrated Developer Environment (IDE) called IntelliJ that comes packaged with all the tools needed to build Scala Projects, as well as to manage them. Finally, we will introduce a few Scala-supported build tools, which are used to managing packages, libraries, and dependencies for your Scala projects.</p><h3>How to Install Scala on Windows</h3><p><strong>Step 1: Ensuring Java Development Kit (JDK) is Installed<br></strong>First and foremost, we must verify that the Windows machine has JDK installed. To do this, open up the command prompt and enter <strong>java -version</strong> and <strong>javac -version</strong>. To work with the latest version of Scala, both Java and Javac versions must be at least 1.8. If needed, you can download the JDK for your machine from <a href="https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Oracle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*7zqfNcOtGD8LzPRdTCd0QQ.png" /></figure><p>Notice the <strong>cd</strong> command (change directory) at the beginning. If command prompt returned both versions without issue, then you can ignore this. Otherwise, you may have likely encountered the following error after entering javac -version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*fGoQGT6aVlOEjI2JpeaVQQ.png" /></figure><p>If this happens and you are sure that you have installed JDK on your computer, then it is likely that Windows is not looking in the path where the JDK files were installed. The solution is to manually navigate to the directory where the files are, in which case you should use the <strong>cd</strong> command followed by the directory.</p><p><strong>Step 2: Download and Install IntelliJ IDE and the Scala Language<br></strong>Now we need to download the necessary tools to install and run Scala code.In this guide, we will use the IntelliJ IDE to install and run Scala code, which also comes with necessary tools required to run Scala programs, namely the SBT. You can download .exe installation file from <a href="https://www.jetbrains.com/idea/download/#section=windows">jetbrains</a>. Make sure to download the <strong>Community Edition</strong>, which is the free version!</p><p>Now run the .exe and walk through the installation. There are no specific installation preferences that need to be set, so it is okay to click <strong>next </strong>and install with default settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*5Tz1yDor3K3KI9nhY3lnAA.png" /></figure><p>After the installation finishes, run the IntelliJ IDE and accept the Terms of Agreement. When you reach the welcome window, navigate to <strong>configure &gt; plugins</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*wLpIC8wzQz3JhYbNFm6_mw.png" /></figure><p>From the plugins window, find Scala and select <strong>Install</strong>. If Scala does not immediately show in the results, use the search bar at the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*5-jQCi3DObGXv9SaDQHepQ.png" /></figure><p>After installing, you must restart the IDE to activate changes in the plugins. Click <strong>Restart IDE</strong> where the Install button was, or simply close and reopen the IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*FRDhydabWt5h99OCd7lz7Q.png" /></figure><p>Congratulations! You have successfully installed Scala and a compatible IDE for Windows.</p><h3>How to Install Scala on Linux</h3><p><strong>Step 1: Ensuring Java Development Kit (JDK) is Installed<br></strong>Similarly to Windows, JDK must be installed on the Linux machine. To verify this, open the terminal and enter the commands <strong>java -version</strong> and <strong>javac -version</strong>. Again, the latest version of Scala requires both Java and Javac versions to be at least 1.8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JD_I3IzrGhLRdrG8Gd-_oA.png" /></figure><p>If you receive an error that Java is an unrecognized command, then you need to install the Java Runtime Environment (JRE). This can easily be done by entering the command <strong>sudo apt-get install openjdk-8-jre-headless </strong>into the terminal. If you get a similar error for Javac, then you are missing the JDK, which you can install with the command <strong>sudo apt-get install openjdk-8-jdk-headless</strong>.</p><p><strong>Step 2: Download and Install IntelliJ IDE and the Scala Language<br></strong>Now we will download and install the necessary tools to install and work with Scala. The IntelliJ IDE comes with every we need including the necessary build tools, and can be downloaded from <a href="https://www.jetbrains.com/idea/download/#section=linux">Jetbrains</a>.</p><p>After downloading the IntelliJ binaries, unpack the files from the terminal with the command <strong>tar xfz ideaIC-XXXX.tar.gx</strong>, where <strong>XXXX</strong> is the version number of your download.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*q48aE5Gs-aTyaoniJ0EcKw.png" /></figure><p>Now using the <strong>cd </strong>command, navigate to the new folder of the unpacked files, and into the <strong>bin </strong>folder. From here, run the idea.sh file with the command <strong>./idea.sh</strong>. This should begin the installation of the IntelliJ IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Wq5K6FYLgLER84BC57d1eQ.png" /></figure><p>The installation window should display automatically. As you go through the installation process, you will eventually arrive at a screen for Featured Plugins that gives the option to install Scala. Select <strong>Install</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*vH0zZpeX8nBL90I5tEnvvA.png" /></figure><p>At this point you can click the <strong>Start using IntelliJ IDEA </strong>button. Congratulations, you have successfully installed IntelliJ and Scala for Linux!</p><h3>Running a Simple Scala Program: Hello World</h3><p>We are almost ready to write and run Scala code. Assuming that you have followed our installation guide, the following instructions should work for both Windows and Linux.</p><p><strong>Step 1: Creating a New Scala Project in IntelliJ<br></strong>Begin by opening up IntelliJ, and select <strong>Create New Project</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*DZxCX5I9cTh3wXr9wEpyeQ.png" /></figure><p>For the project type, select <strong>Scala</strong> on the left pane, and <strong>sbt </strong>on the right pane. Then click <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*kB5gRAKbbFTgK6irlSQV5A.png" /></figure><p>Now enter a name for your project, such as <strong>HelloWorld</strong>. Next to the sbt and Scala versions, make sure to check the boxes that say sources. DO NOT press Finish yet!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*X_yjlvUcFANfqMlG5baZLw.png" /></figure><p>Before we can continue, we must set the JDK. Click <strong>New</strong>, and navigate to the folder where your JDK is installed. Then click <strong>OK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*hZ3eStUbvgPzCnajbj_D4g.png" /></figure><p>Now we can click <strong>Finish</strong> and let IntelliJ generate the project structure. IntelliJ will synchronize the necessary dependencies for sbt, and will let you know when it finishes in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*160dFFtNUjtvFcBnrNIK9w.png" /></figure><p>Next we will add the Scala SDK to our project. This is a CRUCIAL but one-time-only step, so this step will no longer be necessary for creating a new Scala project after this. Right-click on your project in the project pane, and select <strong>Add Framework Support</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*ZrREKJxTJ_JOlxo8buhVmQ.png" /></figure><p>Select Scala, and notice that there is no library selected. Click the <strong>Create</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*SLbTyBBYiBI0DjMsIR27FA.png" /></figure><p>In the resulting window, click <strong>download</strong>. Confirm the Scala SDK version you want and click <strong>OK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*gEVZPbGU-0gHWPF6gqt9Tw.png" /></figure><p>The Scala SDK should apply itself automatically once finished downloading, and the library should now indicate that it is using the SDK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*wqMdj_u8NU6jRXECSmZauA.png" /></figure><p>Finally, we are done setting up the project, and are ready to write Scala code. In the project pane, navigate to <strong>HelloWorld &gt; src &gt; main &gt; scala</strong>. Right-click the scala folder, and select <strong>New &gt; Scala Class</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*X_QuuxOQ9HIXilYu05hzEA.png" /></figure><p>In the resulting window, click the drop-down menu and change the Kind to <strong>Object</strong>. Give a name to your new object and click <strong>OK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Lbjdyv4iAqOhxvjjNmuQgA.png" /></figure><p>IntelliJ should automatically create an outline of the code for your new object. We will slightly modify it so it may perform the typical Hello World function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*XeLhmEMPACyMPwaBxSjITA.png" /></figure><p>Now let’s run our code! From the menu bar, select <strong>Run &gt; Run</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*J99kPV7PovkgH594rwTOOA.png" /></figure><p>Now select the object you just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*wEstzToY3SRs-W74Spc3XQ.png" /></figure><p>If all goes well, the console at the bottom of the IDE will display the program output, and confirm that your program successfully executed and terminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*dShZvqCMj41zTVUiLhf50Q.png" /></figure><p>Now you are ready to start experimenting with Scala code! Remember that Scala runs on the JVM, therefore the same code can be executed on almost every platform, assuming that all of the dependencies and SDK/JDK configurations remain compatible. For a head start on the language’s syntax and features, check out the <a href="https://docs.scala-lang.org/cheatsheets/index.html">Scala Cheatsheet</a> featured on the official Scala website.</p><h3>Managing Packages, Libraries, and Dependencies</h3><p>Many programmers use package managers to easily automate the installation, removal, and configuration of software packages for their programs. In the case of Scala, various build tools are used according to the requirement of the program, instead of package managers. We will now look at some of the most used build tools, their functions, and how they affect the building of the program.</p><h3><strong><em>sbt — simple build tool</em></strong></h3><p>sbt is the one of the most well known build tool used for Scala. It was the first build tool and hence consists of a large set of plugins and integrations. It is for this reason that it is one of the most reliable build tools used in Scala programming.</p><p><strong>Installing sbt<br></strong>sbt can be downloaded and installed from different sites for different OS. For Windows, MSI can be used for the installation. For Mac, sbt is available on Homebrew, and can be installed by using the command <strong>brew install sbt@1</strong>. For Linux such as RedHat or Debian, packages can be used for the installation of sbt.</p><p><strong>Creating a New Project<br></strong>sbt consists of different templates which help while creating a new project. For example Giter8 is one such template which can be used to create a new project. Different templates can be used according to the need of the program like for a simple project, scala-seed template can be used.</p><p>This is how a scala seed template looks like for creating a simple project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*CgxT8I36RmZXDEG9g86A3Q.png" /></figure><p><strong>Defining the Build<br></strong>A build.sbt file located at the root of the project is used by sbt to define the build of the program. More build definitions can be added to the project directory as Scala files. Using the template we end up with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*d8fupjITNGm6qqKTY3t50A.png" /></figure><p><strong>Running the Project<br></strong>To run a project using sbt build tool we have 2 options. One option is to run the program using the command line shell directly. The other option is to use the sbt-shell, which comparatively faster than using the command line. The sbt shell can be started simply by starting sbt with the command <strong>sbt:sbt-test&gt;</strong></p><p><strong>Dependencies in sbt <br></strong> Dependencies in sbt should be structured for better building of the program. The dependencies are added using sbt’s DSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Wc_ouuU2D34X8d74O9CfMQ.png" /></figure><p>The <strong>%%</strong> notation is used to mark the dependency. The important thing to make sure is using the correct dependency according to the Scala version. These dependencies can be added using the library settings with the <strong>+=</strong> operator.</p><p><strong>Defining Custom Tasks:<br></strong>sbt allows the users to define their own tasks, resolution and definition layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*doqE6n77_4iemhwQzvXnRw.png" /></figure><p>The task key is used to define the task. This acts as an interface with type, name and description of the task. For example, in the above code, name is taskKey, type is string, and the description is in the parenthesis. All that is left is to implement the interface.</p><p><strong>Documentation, Community, and Plugins<br></strong>sbt documentation is very refined and complete. Since sbt has been around for longer than most other Scala-supported build tools, its community is fairly extensive, and has acquired a large number of plugins, most of which are mentioned in the Github organization.</p><h3>Cbt — Chris’ build tool</h3><p>Cbt is an abbreviation of Chris’ Build Tool. It was created by Christopher Vogt as an additional build tool apart from sbt. Unlike sbt, Cbt maps the execution of task to JVM invocations and does not add its own layer in between.</p><p><strong>Installing Cbt<br></strong>For the installation of cbt, cbt repository is cloned and the directory is added to the path. Use the command git clone <a href="https://github.com/cvogt/cbt.git">https://github.com/cvogt/cbt.git</a>.</p><p>After the execution for the first time, it suggests using nailgun for faster execution. In Homebrew, nailgun can be installed with the command <strong>brew install nailgun</strong>.</p><p><strong>Creating a New Project<br></strong>After the installing Cbt, we can use it to create a new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*HoBdoQBDDsTOk_mQOVmhWg.png" /></figure><p><strong>Defining the Build<br></strong> If there is already a defined build file, then cbt will use it to set its build settings. We can also let cbt create a new build file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*zIhzRnqcfXRlS2WTZOmSNA.png" /></figure><p><strong>Running the Project<br></strong>In sbt, we had option of using common shell or the sbt shell. But in Cbt, there is no individual shell so the tasks has to be executed directly from the common shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*FiCjuJK_GeLe6JhxOLe2Jw.png" /></figure><p><strong>Dependencies in Cbt<br></strong> sbt DSL is supported in Cbt, which helps in incorporating dependencies from README files using copy and paste. Apart from that, ScalaDependency and MavenDependency can be used to express the dependencies, though these would have to be nested under a Resolver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*HFZOEa9ipJ317-w6uJtYHA.png" /></figure><p><strong>Defining Custom Tasks<br></strong>In Cbt, creating custom tasks is very easy. One only need to create a new function in the build file and call the task from the Cbt afterwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*ZFpE-GX_NqrE1L55yZ9fHw.png" /></figure><p><strong>Documentation, Community and Plugins<br></strong>Cbt is not as vast as sbt but it does have a few plugins and a small community. The documentation would be helpful in the start but you would have to learn on your own after some time.</p><h3><strong>Mill</strong></h3><p>Mill is rather young build tool as compared to other but contains most of the functionalities of sbt. It is faster, easier and simple. In a nutshell better than sbt. The reason for this is, with sbt one can do a thing in many ways which sometimes results in user doing many unnecessary things to do one thing. In Mill, you only have one way. It provides faster initialization and updates the build files automatically, in case anything is changed.</p><p><strong>Installing Mill<br></strong>For windows, Mill can be installed by simply downloading the bat file. For Linux, an AUR package can be downloaded. For OS X, Mill is available on brew package, and can be installed from brew package with the <strong>brew install mill </strong>command.</p><p><strong>Creating a New Project<br></strong>Mill currently doesn’t have any method or mechanism to generate a new project.</p><p><strong>Defining the Build<br></strong>The build file is defined in the root file of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*RMsbFaw0IlsdrAgAOfTHGw.png" /></figure><p>The above code shows how the build definition in Mill looks like. The build structure of the project looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*y2f29rN_VJ7zpnY5wdGi7A.png" /></figure><p>The structure of project in Mill is almost like the structure of Maven. Mill doesn’t pose any restriction on the structure but instead allows the flexibility of the modules. Its structure is also sbt compatible.</p><p><strong>Running the Project<br></strong>Mill has a module.task file which dictates a common syntax for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*ECAmI1wIqWWM7FKPPAazpw.png" /></figure><p><strong>Dependencies in Mill<br></strong> Like sbt, Mill also uses DSL to add dependencies to the project, only instead of using <strong>%%</strong> for dependencies Mill uses <strong>::</strong> notation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*M7TAYE0P-GPuebiJmwUj3w.png" /></figure><p><strong>Defining Custom Tasks<br></strong>Mill handles task definition, ordering and cache by using its own defined task graph abstraction. When one task is called from another, it creates dependencies. There are 3 different types of tasks:</p><ol><li><strong>Targets</strong>: It is used to define where the output is generated,compiled or assembled.</li><li><strong>Sources</strong>: It defines where the code is originated from.</li><li><strong>Commands</strong>: it defines the things to do. For example, a task defined as:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*fzs5LmARfHxO8MTja0yi5Q.png" /></figure><p>will produce the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*KKgFyd5Wj9al3qcdEGhkLg.png" /></figure><p><strong>Documentation, Community and Modules<br></strong>Mill has a complete documentation at <a href="http://www.lihaoyi.com/mill/">http://www.lihaoyi.com/mill/</a> and a very active community. Mill uses modules instead of plugins.</p><h3><strong>Other Build Tools</strong></h3><p>There are many build tools other than the ones we covered; too many to be discussed extensively in a single guide. For example, there is <strong>Gradle</strong>, which can also be used as a build tool for the scala project using Gradle-Scala plugin. There is also <strong>Fury</strong>, a fairly new build tool recently launched, whose documentation and community is only starting to grow. We also have <strong>Maven </strong>and <strong>Polyglot Maven</strong>, which can be used if one wants to use Maven in their project. At the time of this writing, there are also some build tools currently in early development , such as <strong>Ant</strong>,<strong> Bazel</strong>,<strong> Pants</strong>,<strong> </strong>and <strong>Make</strong>.</p><h3>How to choose a Build Tool?</h3><p>Since each build tool specializes in different programming needs, the decisive factor in choosing the build for you should be based on your needs. If you’re considering a specific build tool to use, checking the documentation would be a good place to start.</p><p>sbt is the most effective and popular build tool used for Scala programming. For simple projects with straight-forward needs which are well documented, sbt can be used. Sbt is mostly used by experienced programmers. For beginners, using sbt for the parts which are not documented will be really difficult, so in these cases it is well suggested to use Mill instead of sbt.</p><p><strong>Authors:<br></strong>Alessandro Heres — <a href="https://github.com/alexheres">Github</a><br>Tristen Sprainis — <a href="https://github.com/Tsprainis">Github</a><br>Ayushi Priyadarshi — <a href="https://github.com/ayupriya">Github</a> | <a href="https://www.linkedin.com/in/ayushi-priyadarshi-21b237145">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33464b390d57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>