<?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 ScalaTips on Medium]]></title>
        <description><![CDATA[Stories by ScalaTips on Medium]]></description>
        <link>https://medium.com/@gakk.joroh?source=rss-faf13f4e367d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zzpQLBMuAdz3bbJzFPM7Fg.png</url>
            <title>Stories by ScalaTips on Medium</title>
            <link>https://medium.com/@gakk.joroh?source=rss-faf13f4e367d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:48:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gakk.joroh/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 call-by-name vs call-by-value]]></title>
            <link>https://medium.com/@gakk.joroh/scala-call-by-name-vs-call-by-value-7dd3e48afb2a?source=rss-faf13f4e367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd3e48afb2a</guid>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[ScalaTips]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 14:22:50 GMT</pubDate>
            <atom:updated>2023-02-15T14:22:50.039Z</atom:updated>
            <content:encoded><![CDATA[<p>Scala supports two argument passing mechanisms.</p><p><strong>call-by-value</strong></p><p>This is the default behavior of Scala arguments, and it’s similar to <strong>pass-by-value</strong> approach in Java. Everything is an object in Scala, there aren’t any primitives, variables contain memory location of objects. Here we are passing the memory address of objects, as arguments. Let’s use a small program to demonstrate this behavior.</p><pre>class NumberWrapper(var value: Int)<br><br>val num = new NumberWrapper(10)<br><br>def increaseByOne(num: NumberWrapper): Unit = { <br>  num.value = num.value + 1 <br>}<br><br>println(&quot;value is &quot; + num.value)                                // prints -&gt;  value is 10<br>increaseByOne(num) <br>println(&quot;value after update is &quot; + num.value)                    // prints -&gt; value is 11<br><br>/** <br> * value is 10 <br> * value after update is 11 <br> * value after update outside function scope is 11 <br> */</pre><p>As we can see from this example. Behavior is similar to Java, only the reference to <em>num</em> object is being passed as a value to the <strong><em>increaseByOne</em></strong><em> </em>function. It’s still the same object inside and outside the scope of the function.</p><p>But the interesting factor about <strong>call-by-value</strong> mechanism is, its evaluation time. Replace your arguments with expressions, how those expressions are evaluated before passing into the function. Let’s take another example.</p><pre>var a:Int = 0 <br>def intGenerator: Int = { <br>  println(&quot;executing intGenerator method&quot;) <br>  a = a + 1 <br>  a <br>}<br><br>def callByValuePrintTwice(num: Int): Unit = { <br>  println(&quot;executing callByValue method&quot;) <br>  println(num) <br>  println(num) <br>}<br><br>callByValuePrintTwice(intGenerator)<br><br>// output<br>&gt; executing intGenerator method <br>&gt; executing callByValue method <br>&gt; 1 <br>&gt; 1</pre><p>The function <strong><em>intGenerator </em></strong>returns an integer, and with each subsequent call to the function, the value it returns is incremented by one. And then we have this <strong><em>callByValuePrintTwice</em></strong> function to consume an integer and prints that integer twice. Finally we are passing the return value of the <strong><em>intGenerator </em></strong>function as an argument to the <strong><em>callByValuePrintTwice </em></strong>function. Now check the output of this code segment. Even we are using the integer parameter twice inside the <strong><em>callByValuePrintTwice </em></strong>function, <strong><em>intGenerator</em></strong> function is invoked only once. Which means no matter how many times we are using the parameter inside the function/method, arguments are evaluated only at invoke time.</p><p><strong>call-by-name</strong></p><p>We have to explicitly make arguments <strong>call-by-name</strong> by placing =&gt; sign between parameter name and it’s type. Here the difference is is that the arguments are not evaluated at the time the function is called. Instead, they are evaluated each time the parameter is used within the function. Let’s introduce another function to above example.</p><pre>private def callByNamePrintTwice(num: =&gt; Int): Unit = {<br>  println(&quot;executing callByName method&quot;)<br>  println(num)<br>  println(num)<br>}<br><br>callByNamePrintTwice(intGenerator)<br><br>// output<br>&gt; executing callByName method <br>&gt; executing intGenerator method <br>&gt; 1 <br>&gt; executing intGenerator method <br>&gt; 2</pre><p>Looking at the output, we can see, <strong><em>intGenerator</em></strong> method is not evaluated at method invocation time. Instead it was evaluated twice for each time <strong>num</strong> parameter is used inside the <strong><em>callByNamePrintTwice</em></strong> function. So the argument is passed as an expression into the function rather than as an evaluated value.</p><p>Comparing the two strategies, we can say that <strong>call-by-value</strong> can be more efficient or economical, as the argument is evaluated only once regardless of how many times it is used within the function. On the other hand, <strong>call-by-name</strong> can be more flexible, as it allows us to delay the evaluation of the argument and ensure that it is up to date when it is actually used in the function.</p><p>Wanna see a use case of <strong>call-by-value </strong>approach? Why don’t you check the source code of <strong>scala.util.Try</strong> class.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd3e48afb2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala for-comprehension]]></title>
            <link>https://medium.com/@gakk.joroh/scala-for-comprehension-c4f053c3f679?source=rss-faf13f4e367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f053c3f679</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[ScalaTips]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 16:10:08 GMT</pubDate>
            <atom:updated>2023-02-01T16:10:08.278Z</atom:updated>
            <content:encoded><![CDATA[<p>For-comprehensions in the Scala programming language provide a powerful and simple way to loop through data.</p><blockquote><em>Actually, the term comprehension comes from functional programming. It expresses the idea that we are traversing one or more collections of some kind, “comprehending” what we find, and computing something new from it, often another collection.</em></blockquote><ul><li>From Programming Scala, 2nd Edition</li></ul><p>For years, we have utilized simple for loop constructs in Java, known as imperative for loops. In contrast, Scala offers for-comprehensions as an alternative to these Java-style for loops, which are declarative for loops. But what is the difference between imperative and declarative constructs? We need to learn about this first before moving on.</p><p><strong>Imperative vs Declarative programming</strong></p><p>Imperative programming describes how we want the program to solve our problem by executing statements one by one. We kind of decode our problem into small pieces that can be understood by the programming language. Now the code is not the best when it comes to readability. The reader has to put some effort into understanding how the problem is represented in the language.</p><p>Declarative programming focuses on readability and ease of use for the developer. We don’t have to spend much time decoding our problem into programming language understandable constructs here. We can define our expectations as they are, in a more human readable manner. Most languages that support declarative programming have sugar coated syntax and are rendered into smaller instructions at compile time. It doesn’t always have to be a new language; the <strong>Stream </strong>API with lambda expressions in Java caters to declarative programming styles over collections, where conventional Java for-loops are imperative.</p><p>Now back into for-comprehensions.</p><p><strong>For-comprehension syntax</strong></p><p>For a developer coming from an imperative language, for-comprehension syntax can be both simple and complex, depending on the situation.</p><pre>val numList = Seq(1, 2, 3, 4)<br>val nameList = Seq(&quot;John&quot;, &quot;Shane&quot;, &quot;Mark&quot;, &quot;Sara&quot;)<br><br>for(n &lt;- numList) println(n)    //------------ a simple for expression <br>   <br>  val combinationList = for {     //------------ a complex for expression <br>    num &lt;- numList <br>    if num%2 == 0 <br>    name &lt;- nameList <br>    firstChar = name.charAt(0) <br>    if firstChar == &#39;S&#39; <br>  } yield { <br>    // some logic here <br>    (num, name) <br>  }</pre><p>As we can see, syntax can be confusing at the first glance. But we can untangle it into some simple components. Basically for-comprehension has the structure of,</p><pre>for (enumerators) yeild e </pre><p>Here we can provide a list of enumerators. Enumerators can be either generators, filters, or value definitions. Don’t confuse them with <strong>enumerations, </strong>they are a different kind of construct. List of enumerators needs to be wrapped around parentheses or curly brackets. If we are using parentheses, enumerators need to be semi-colon separated. And if we are using curly brackets, we can separate enumerators with new line characters, without using semi-colons. Which is more readable when we have a long list of enumerators.</p><p><strong>Generators</strong></p><p>Generators iterate through a collection of data and generate new values to the for-comprehension construct. Each generator introduces a new variable to the for-comprehension scope. First enumerator of a for-comprehension always has to be a generator, since only they feed data/values into the for expression. It’s possible to use multiple generators inside a single for-comprehension, and such are similar to nested for loops in java. Let’s define some for expressions with generators.</p><pre>val numList = Seq(1, 2, 3, 4) <br>val numList2 = List(10,20,40)<br><br>// for-comprehension with single generator<br>for (n &lt;- numList) print(n + &quot; &quot;) <br>&gt; 1 2 3 4 <br><br>// single line for-comprehension with multiple generators<br>for (n &lt;- numList; m &lt;- numList2) print((n,m) + &quot; &quot;) <br>&gt; (1,10) (1,20) (1,40) (2,10) (2,20) (2,40) (3,10) (3,20) (3,40) (4,10) (4,20) (4,40) <br><br>// multiple line for-comprehension with multiple generators<br>// prints same output as above example<br>  for { <br>    n &lt;- numList <br>    m &lt;- numList2 <br>  } print((n,m) + &quot; &quot;) <br>&gt; (1,10) (1,20) (1,40) (2,10) (2,20) (2,40) (3,10) (3,20) (3,40) (4,10) (4,20) (4,40)</pre><p><strong>Filters/Guards</strong></p><p>Filters or guards contain boolean expressions to remove unwanted values generated from generators. Values that meet the requirements of the boolean expression can continue on. Same as generators, we can include multiple filters in a single for expression.</p><pre>for { <br>    (name, age) &lt;- tourists <br>    if age &lt; 40 <br>    if name.startsWith(&quot;S&quot;) &amp;&amp; name.endsWith(&quot;a&quot;) <br>  } { <br>    // something to do with tourists younger than 40 years, <br>    // and name starts with &#39;S&#39; and ends with &#39;a&#39; <br>  }</pre><p>Above code segment has some stupid logic, as my brain cells couldn’t come up with a realistic example to demonstrate the use of filters. Somehow it has three enumerators; one generator and two filters. In our generator, we are accepting a tuple of two values for each iteration. Since the variables <em>name</em> and <em>age</em> are available throughout the scope of the for comprehension expression, we can use them in the filters as well to specify the boolean expressions. Take note: we are using curly brackets twice here. First to wrap enumerators, and second to wrap the for-comprehension body. We are supposed to define our logic in this second curly bracket-wrapped scope, but I am not intuitive enough to define something useful in it.</p><p>Keep in mind, Scala for-comprehension do not support <strong>break</strong> and <strong>continue </strong>keywords. We are supposed to use filters instead of these keywords.</p><p><strong>Value definitions</strong></p><p>For-comprehension allows us to define variables inside the enumerator list, which will be valid within the scope of the entire for-expression. Value definitions are final variables, we cannot reassign them later.</p><pre>val names = List(&quot;Shawn&quot;, &quot;Mark&quot;, &quot;Lisa&quot;, &quot;Shoker&quot;, &quot;Linda&quot;, &quot;Ben&quot;) <br>  for { <br>    name &lt;- names <br>    firstChar = name.charAt(0) <br>    if firstChar == &#39;S&#39; <br>  } { <br>    // firstChar = &#39;K&#39;  // final variable. cannot reassign <br>    println(name) <br>  }</pre><p><strong>Yield</strong></p><p>Body of the for comprehension is also an expression. Which can have a return value as the last statement. (In Scala we don’t need to use <strong>return</strong> keyword to actually return a value.). But having only a return value does not actually return the outcome of the for-comprehension body. We need to use <strong>yield</strong> keyword between the enumerator list and the body to cater that. Let’s do some changes to the above example.</p><pre>val filteredNames = for { <br>    name &lt;- names <br>    firstChar = name.charAt(0) <br>    if firstChar == &#39;S&#39; <br>  } yield { <br>    // firstChar = &#39;K&#39;  // final variable. cannot reassign<br>    println(name)<br>    name <br>  }</pre><p>This code snippet will return a sequence of strings <strong>Seq[String] </strong>for names starting with character ‘S’. One string per each iteration. If you remove the <strong>yield </strong>keyword, it won’t return anything and type annotation of <strong>filteredNames </strong>variable will be set to Unit.</p><p>That is all I have to share with you guys right now. Let me know if there are any problems with the information provided. I will update this post if I acquire any new knowledge about for-comprehension in my free time.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f053c3f679" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Enumerations]]></title>
            <link>https://medium.com/@gakk.joroh/scala-enumerations-c1cc8ca1d4fe?source=rss-faf13f4e367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1cc8ca1d4fe</guid>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[ScalaTips]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 16:03:53 GMT</pubDate>
            <atom:updated>2023-02-01T16:03:53.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Enumerations are a group of constants from the same type. Enumerated types are a type of container that bundles together enumerations of same category. Many modern programming languages have built-in syntax for defining enumerations, however, Scala, which is known for its rich syntax, does not have specific syntax for enumerations. Instead we have to define an object that extends Enumeration abstract class.</p><p>Let’s create our first enumerated type,</p><pre>object WeekDay extends Enumeration {  <br>  val MON, TUE, WED, THU, FRI, SAT, SUN = Value <br>}</pre><p>Variable defined using <strong>val </strong>keyword are <strong>final </strong>values, and they are <strong>public </strong>by default when we don’t specify access modifiers. Therefore, they are just public, final variables from an Enumeration class. Keep in mind the importance of using <strong>val </strong>keyword. We are defining enumerated constants within the constructor of <strong>WeekDay </strong>object. When not using the <strong>var </strong>or <strong>val </strong>keyword, the constants are only accessible within the constructor scope. But by using the <strong>val </strong>keyword, they are transformed into members of the class, allowing them to be accessed outside the constructor.</p><p>When I was learning Scala Enumeration for the first time, I was confused with this use of <strong>Value</strong>. It seems like a variable, but actually it is a protected method inside <strong>Enumeration </strong>abstract class which return a object of type <strong>Value</strong>. Why protected? because the enumerated constants are intended to be utilized within the subclasses of <strong>Enumeration</strong>. Keep in mind, method <strong>Value </strong>and type of objects returned from that method are two things (Yes, Scala allows us to define classes and variables/methods/functions withing the same scope).</p><p>You can always check the source code of <strong>Enumeration </strong>class and learn them but for me to explain it, I am using a simplified version below.</p><pre>abstract class Enumeration(initial: Int) { <br>  protected var nextId: Int = initial<br><br>  protected final def Value: Value                        = Value(nextId) <br>  protected final def Value(i: Int): Value                = Value(i, nextNameOrNull) <br>  protected final def Value(name: String): Value          = Value(nextId, name) <br>  protected final def Value(i: Int, name: String): Value  = new Value(i, name)<br><br>  abstract class Value { <br>    //---not going to discuss to avoid confusion <br>  } <br>}</pre><p>As you can see, the <strong>Enumeration </strong>abstract class contains several overloaded <strong>Value </strong>methods. We have used used the first method with no arguments in our <strong>WeekDay </strong>example. The <strong>Enumeration </strong>class contains a protected integer variable called <strong>nextId</strong>, which serves as a possible index for the next constant. This index will be increased with each added constant value. We can pass initial <strong>nextId</strong> value in the constructor of the <strong>Enumeration</strong> class, or it will be 0 by default. We can also pass unique custom <strong>Id</strong> values for each enumeration constant if needed. Apart from <strong>id</strong>, we also can pass a <strong>name </strong>to each enumeration value (we will discuss this using an example later).</p><pre>for(day &lt;- WeekDay.values) print(day.id + &quot;, &quot;)<br>&gt; 0, 1, 2, 3, 4, 5, 6,</pre><p>In this example, we are iterating through the enumeration values. <strong>values</strong> is a method in Enumeration class that returns a object of type <strong>ValueSet</strong>. We can iterate through our enumeration thanks to the behaviours of <strong>Valueset </strong>object. In each iteration, we are printing the <strong>id </strong>of the enumeration value. It is important to note that each enumeration value is of the <strong>Value</strong> type, not the <strong>Enumeration</strong> type. Now <strong>id</strong> is a method defined inside the <strong>Value </strong>class to return the unique identifier of the enumeration value.</p><p><strong><em>Fun fact:</em></strong> While <strong>WeekDay</strong> is an <strong>Enumeration</strong> type class, <strong>ValueSet </strong>object used in above example is an <strong>enumerator </strong>for the for-comprehension expression. Don’t get muddled by the difference between enumeration and enumerator. Visit our post about for-comprehension if you are confused.</p><p>As we have learned from the simplified version of <strong>Enumeration </strong>abstract class, we can provide names to each value. Let’s define another example with names on each element.</p><pre>object Months extends Enumeration {<br>  val JAN = Value(&quot;january&quot;) <br>  val FEB = Value(&quot;february&quot;) <br>  val MAR = Value(&quot;march&quot;) <br>}<br><br>for(month &lt;- Months.values) print(month + &quot;, &quot;)<br>&gt; january, february, march,</pre><p><strong>It has no connection with Java Enums</strong></p><p>There is no connection between Scala <strong>Enumeration </strong>objects and Java <strong>enum</strong>, as <strong>Enumerations </strong>does not compile into Java <strong>enums</strong>. Java <strong>enums </strong>are compiled into a class extending from <strong>java.lang.Enum</strong>, which each <strong>enum </strong>values are compiled into public static final variables. Ironically Scala, a language with a lot of syntactical sugar decided not to use syntactical sugar in their <strong>Enumerations</strong>.</p><p>There are a lot to discuss about Scala Enumeration class. I will try to write more about them with time. And if you find any issues with above content please leave a comment and let me know.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1cc8ca1d4fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Constructors]]></title>
            <link>https://medium.com/@gakk.joroh/scala-constructors-b5731587c43c?source=rss-faf13f4e367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5731587c43c</guid>
            <category><![CDATA[scala-programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[ScalaTips]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 15:57:12 GMT</pubDate>
            <atom:updated>2023-02-01T15:57:12.063Z</atom:updated>
            <content:encoded><![CDATA[<p>Constructors are used to create objects. If you are coming from Java, like me, then constructors might have been a straightforward concept for you. But in Scala, this concept is bit more complex.</p><p>There are two types of constructors in Scala.</p><ol><li>Primary constructors</li><li>Auxiliary constructors</li></ol><p><strong>Primary constructors</strong></p><p>Let’s start from an example class with a simple primary constructor.</p><pre>class Student(id: Int, name: String) { <br>  println(&quot;hello from primary constructor&quot;) <br>}<br><br>val s1 = new Student(1, &quot;john&quot;)<br>&gt; hello from primary constructor</pre><p>There can be only one primary constructor per class definition. As we can see, the primary constructor is bound into the <strong>Student </strong>class itself. Statements we write inside the class body (curly brackets) are part of the primary constructor. Class body except for method definitions inside the class, can be argued to be the constructor body.</p><p>When you don’t have parameters in your constructor, Scala defines a default primary constructor by itself.</p><p>There is a special case about parameter-less constructors in Scala classes. Specifying parentheses is optional when there are no parameters in your class’s primary constructor. For both class definition and constructor invocation.</p><pre>class A { }<br>class B() {}<br><br>val a1 = new A<br>val a2 = new A()<br>val b1 = new B<br>val b2 = new B()</pre><p>As above code snippet suggests, final outcome will be the same regardless of the parentheses.</p><p><strong>Auxiliary (secondary) constructors</strong></p><p>Any constructor except the primary constructor is called an auxiliary constructor. Can define multiple such constructors with <strong>this </strong>keyword, but with different signatures. The first statement of any auxiliary constructor should call the primary constructor. Let’s define an auxiliary constructor with those rules.</p><pre>class Student(id: Int, name: String) { <br>  println(&quot;hello from primary constructor&quot;) <br>  <br>  def this(name: String) = { <br>    this(0, name) <br>    println(&quot;hello from auxiliary constructor&quot;) <br>  } <br>}<br><br>val s2 = new Student(&quot;smith&quot;)<br>&gt; hello from primary constructor<br>&gt; hello from auxiliary constructor</pre><p><strong>Invoking superclass constructor</strong></p><p>Only the primary constructor is allowed to invoke superclass constructors. Auxiliary constructors can only call the primary constructor of the same class. When a superclass has multiple constructors, the primary constructor of the subclass can decide which super- constructor to be invoked. Let’s take an example to describe this situation.</p><pre>class Person(age: Int, name: String) { <br>  println(&quot;primary constructor of Person&quot;) <br>  def this(name: String) = { <br>    this(0, name) <br>    println(&quot;auxiliary constructor of Person&quot;) <br>  } <br>}<br><br>// calls auxiliary constructor of superclass<br>class Employee(empId: Int, age: Int, name: String) extends Person(name) { <br>  println(&quot;primary constructor for Employee&quot;) <br>  def this(empId: Int, name: String) = { <br>    this(empId, 0, name) <br>    println(&quot;auxiliary constructor of Employee&quot;) <br>  } <br>}<br><br>// calls primary constructor of superclass<br>class EmployeeTwo(empId: Int, age: Int, name: String) extends Person(age, name) {}</pre><p>As we can see in the example, we can define our class to invoke any superclass constructor.</p><p><strong>Scope of constructor parameters in Scala</strong></p><p>The scope of auxiliary constructor parameters is always limited to the block in which they are defined. Parameters we define inside the primary constructor are fields for the object. The scope and behavior of these fields are determined by how they are defined. And it can be a bit tricky. So, let’s look at some examples and try to learn from them.</p><pre>class Dog(name: String) {}                            //-----(1)<br>class Dog(val name: String) {}                        //-----(2)<br>class Dog(var name: String) {}                        //-----(3)<br>class Dog(private var name: String) {}                //-----(4)</pre><ol><li>Constructor parameters without <em>val</em> or <em>var </em>keywords<em> </em>are primary and immutable by default. Internally it should look like <strong>private[this] val name: String.</strong> Cannot access them outside the <strong>object</strong>.</li><li>Now parameter is still immutable, but access modifier is set to default value, which is public in Scala. Can access them outside the class, but cannot change the value.</li><li>Parameter is mutable, and access modifier is public. Can access and modify them outside the class definition.</li><li>Parameter is mutable but private to the class definition. Cannot access or modify outside the <strong>class</strong> definition. But both are possible within <strong>class</strong> definition.</li></ol><p><strong>Access modifiers for constructors</strong></p><p>In Scala, there are three access modifiers that can be used for constructors: private, protected, and public. By default, constructors are public. Public constructors can be accessed anywhere in our program, while others have some restrictions. Let’s define some constructors with different access privileges and discuss.</p><pre>class Animal(age: Int) {}                //-----public/default constructor<br>class Animal private (age: Int) {}       //-----private constructor<br>class Animal protected (age: Int) {}     //-----protected constructor<br>class Animal private {}                  //-----protected constructor without any parameters</pre><p>Private keyword before the constructor definition makes it visible only for the class itself and companion object. Use case is to hide the constructor and provide other means of instantiation, like using companion objects or builders. We cannot use <strong>new </strong>keyword from an outside entity. Keep in mind that private constructors restrict the class from inheritance. You cannot extend from a private class.</p><p>Protected constructors have similar visibility, but they can be inherited from, and sub classes can access super class constructor.</p><p>That’s it for now about Scala constructors. Thank you and please let me know if you have any concerns regarding this content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5731587c43c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scala Traits]]></title>
            <link>https://medium.com/@gakk.joroh/scala-traits-b0023da31722?source=rss-faf13f4e367d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0023da31722</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[scala-programming]]></category>
            <dc:creator><![CDATA[ScalaTips]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 15:46:51 GMT</pubDate>
            <atom:updated>2023-02-01T15:46:51.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Traits are similar to Java interfaces, and they are compiled into Java interfaces. But they are not exactly the same.</p><p>Check this very simple trait definition:</p><pre>trait Human {<br>  def eat(): Unit<br>  def walk(): Unit<br>  def greet: string<br>}</pre><p>Classes, objects, and other traits can inherit from traits. Assume you have defined a trait called BarkerTrait. Now you can inherit from that trait as follows:</p><pre>&gt; class DogClass extends BarkerTrait<br>&gt; object HuskyObject extends BarkerTrait<br>&gt; trait DogTrait extends BarkerTrait<br>&gt; class DogClass extends AnimalClass with BarkerTrait</pre><p>Java interfaces can only inherit from other interfaces. But unlike Java, Scala traits can inherit from both classes and other traits. (Keep in mind, you cannot inherit from Scala object definitions)</p><pre>&gt; trait BarkerTrait extends TalkerTrait<br>&gt; trait BarkerTrait extends AnimalClass<br>&gt; trait BarkerTrait extends AnimalClass with TalkerTrait</pre><p>Scala allows you to have concrete members inside trait definitions. Scala traits that contain code are called mixins. But what exactly can be recognized as code in mixins?</p><ol><li>Concrete/non-abstract method definitions.</li><li>Variables/fields</li><li>Constructors without parameters</li></ol><p>We can call the above things “code,” “concrete members,” or “non-abstract members” of a mixin trait.</p><p>Check the following mixin trait with concrete members:</p><pre>trait Human {<br>  val name = “Human Name”<br>  def eat(): Unit<br>  def walk(): Unit<br>  def greet: String = “Hi my name is “ + name + “.”<br>}</pre><p>When a trait has abstract methods, you have to override and implement them inside the trait’s non-abstract child classes or objects. Check the following example class extended from Human mixin trait:</p><pre>class CountryMan extends Human {<br>   override def eat(): Unit = {<br>      println(&quot;eat like a countryman.&quot;)<br>      println(&quot;take a nap after eating&quot;)<br>   }<br><br>   override def walk() = println(&quot;walk on top of the mountains&quot;)<br>}</pre><p>Traits cannot be instantiated. They cannot have parameterized constructors, yet they can parameter less constructors. (Scala 3 traits can have parameters).</p><p>Scala trait is a large topic that cannot be covered in a single article. I am planning to cover more details in future articles.</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0023da31722" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>