Scala Type System

Scala Type System is quite rich (that also means it is a huge) and offers lots of options. Unfortunately, this also means that we cannot cover the type system in one blog entry. Before we dive into the depths of Scala type system let’s just understand the various components it is made up of so that we can appreciate how rich it is. Scala type system can be divided into the following. Scala Predefined Types Parameterised Types Custom types Abstract Types Bounds Variances Type classes Scala PreDefined Types So, as you can see this is a really wide area. Let’s start with the simplest of them all the predefined types. Pre-defined types in Scala are the primitive types like int, string etc. To understand it simply let’s see the most used Scala type hierarchy diagram. See Below Let’s try and understand this Scala type hierarchy as a first step. Any … Read more

Scala – Classes & Objects

OOps is that correct? Scala is always related to Functional Programming. However, as you may have guessed by now it also supports Object-Oriented Programming constructs. We can in Scala use OOPs & FP constructs in quite interesting ways. But before we start doing that let’s just start looking at the basics of Scala classes. Scala improves upon Java classes in some ways. It does away with a lot of boiler-plate code which the developers needed to write during Java development. Some of those concepts are discussed below. Keep in mind that all this is already well known and if you are a Java developer it is just a slightly different syntax and a few features thrown in which make the life of a developer a bit easy(Supposedly!) Let’s begin with a Basic syntax. See Below In the above example, we create a class called color which has a public method … Read more

Scala – Enumeratum

Enumeratum is a third party enumeration library for Scala. It is also probably the most used enumeration library amongst all scala developers. It is also quite similar to Scala enumerations so using it is quite easy. To start using enumeratum, it needs to be imported into the Scala project. In the build.sbt add the following. See Below Using enumeratum is pretty simple. See Below Let’s go thru the code line by line The first line to look at is the import enumeratum._ which is pretty self-explanatory. The next line sealed trait Color extends EnumEntry creates a sealed trait called Color which extends an enumeratum trait called EnumEntry. findValues is a protected method which invokes a macro Finally, we have our Enum values. Enumeratum provides methods similar to Scala enumerations library for checking index, retrieving a list of values. Additional attributes can be added to the enumerations using enumeratum. See Below … Read more

Scala – Enumerations

Enumerations represent meaningful descriptions for more primitive data types. Scala Enumeration trait can be used to define a finite set of values. Let’s see a simple declaration and understand what it all means The first line is extending the Enumeration trait The second line is a declaration of type alias so that it makes the code a bit more meaningful instead of just saying Value – for example declaring a function In the third line – at the end, it says Value, which is a method and not the type Value mentioned in the second line. This method returns a type Value. Each element of an enum has a unique running id, which is auto-incremented automatically at the time of assignment. Specific values can also be assigned the elements in scala enumerations. See Below Enumerations can be passed to functions. However, there are a couple of issues, if values other than the ones in … Read more

Scala – Case Objects

Case Objects are singleton objects similar to an object with the modifier case. Similar to case classes a lot of boilerplate code is added to when the object is prefixed with the modifer case. Case objects are also serializable as is the case with case classes which is really useful when you are using frameworks like Akka. Defining case objects is simple. See Below Case Objects are quite similar to case classes. They can have members and have some of the same methods like toString, hashCode. Similarly, it is important to understand that some of the methods available in case classes are not available to case objects, for example, apply, unapply. Sealed Case Objects One of the variations of case objects is the sealed case objects. Sealed Case objects are an interesting alternative to the enumeration trait. If you want a peek into scala enumeration trait before diving into sealed case objects, … Read more

Scala Traits

Traits in Scala are similar to interfaces in Java. However, they offer substantial enhancements to Java interfaces. They can also be used in Java classes under certain conditions. Traits encapsulate methods and fields which can be reused and mixed with classes. Scala allows both abstract and concrete methods and variables, unlike Java interfaces which have only abstract methods. So in some sense traits are like similar to classes except that it has a keyword trait in front of it when it is defined. Let’s define a trait which has two abstract variables and one abstract method. See Below Extending Traits Traits can be extended to create new traits. See Below While extending traits it is not necessary to implement the abstract methods. It is also possible to create traits with a mix of abstract and concrete methods which was not possible in Java. See Below Extending Classes with Traits Once … Read more

Scala – Pattern Matching & Case Classes

Pattern matching is also applied to case classes. Rather patter matching is always discussed along with case classes. Let’s see how we can apply pattern matching to case classes. Let’s look at an example. See Below In the above example, there is a Person case class defined and a match-case pattern matching function is defined which checks the lastName element of the Person class. If the lastName is Doe it prints that it has “Found a Doe!” and if it lastName is Cole it prints it has “Found a Cole!!”, otherwise, it prints “Unknown Last Name”. Let’s start to mix up – In one of the first blog entry of Pattern matching we had discussed Or clause in values. We can use it in case classes as well. See Below The result is whenever the lastName is Cole or Doe it will print “Found a Doe or Cole!”. Now let’s apply … Read more

Scala – Pattern Matching & Collections

Pattern matching is not just limited to simple types it can also be applied to collections as well. Let’s see how it can be applied to Lists. See Below In the above example, we want to check if the list of 3 elements starts with 10 or not. This logic works fine when the list has just 3 elements. But fails if the list has more than 3 elements. The last print shows the failure condition.  Extending the logic so that lists of any size can be checked. See Below. In the above code, the only change we made was in the second line of the function and introduced _* – is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence. It is not as complicated as it sounds essentially it means you can pass multiple … Read more

Scala – Pattern Matching – Values, Types & Variables

Pattern matching in Scala is one of the most widely used and discussed topics. In simple terms, it is similar to the switch-case. Let’s use that familiarity to get a simple understanding of pattern matching and build up from there. Let’s first look at a simple match-case expression and see how it works. In the above example, we have a function called multiply, which takes a parameter and returns a value. If the value is 4 it will multiply the value by 3. Underscore _ acts as a catch-all for any other values and it will multiply by 2. This is simple. But what if we want to apply the same logic for more than one patterns. Writing individual case statements would make the code unnecessarily long. Let’s apply an OR logic to the expression. In the above example, we have a function called multiply, which takes a parameter and returns … Read more

Scala – Case Classes

Computing is all about logic and data. Various languages provide different ways to handle data. Primitive data types like Int, String and Boolean are usually never enough to represent anything meaningful by themselves. For example – If we were to capture the details of a Person – it will consist of many attributes. First Name, Last Name, Age, email Id etc. The real-world data is more complex and is made up of different primitive data types. Scala provides a clean way of putting and aggregating all this data together into immutable structures called case classes. Case classes are defined as normal classes except the definition is pre-fixed by a modifier case. Case classes provide a lot of boilerplate code, which reduces the amount of code which needs to be written to handle complex aggregated data. Cases classes are also very useful in pattern matching and if you are working with … Read more