Programming in Scala Gist 3

Vinu Charanya
vTechNotes
Published in
7 min readMay 25, 2016

These are the key points from the Programming in Scala, Second Edition by Martin Odersky, Lex Spoon, Bill Venners. I wanted to make note of some key points. They may seem broken and not make much sense, if you have not read the book. This is for personal reference. Feel free to correct me if I have interpreted anything wrong in this post.

Chapter 3 — Next Steps in Scala

Continued from Programming in Scala Gist 2

7. Parameterize arrays with types

  • Class objects are instantiated with new. An instantiated object in Scala can be parameterized(configured) with values and types by passing objects to a constructor.
Eg., Parameterizing on object instantiation
  • When an instance is parameterized with both type and value, type comes first in [] followed by values in ()
  • Arrays in Scala are accessed by placing the index inside () and not []. Arrays are invoked with () because they are simply instances of classes like any other class in Scala.
  • If a method in Scala takes only one parameter you can call it without a dot or parenthesis. (0).to(2) → 0 to 2 Only works if the receiver of the method call is explicitly specified. “println 1o” ❌ | “Console println 10” ✔️
  • Scala doesn’t have operator overloading because it doesn’t actually have operators in the traditional sense as characters such as +, -, * and / can be used in method names. 1 +2 → (1).+(2)
  • Accessing an element of an array is a method call as well — When you apply parenthesis surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. Eg., animals(1) → animals.apply(1)
  • Any application of an object to some arguments in parentheses will be transformed to an apply method call. If the object class doesn’t have an apply method, Scala with throw a compile error.
  • Scala achieves conceptual simplicity by treating everything from arrays to expressions as objects with methods. This uniformity does not incur a significant performance cost.
  • When an assignment is made to a variable to which parentheses and one or more arguments have been applied, the compiler will transform that into an invocation of an update method that takes the arguments in parentheses as well as the object to the right of the equal sign.
Eg: update method in Scala
  • A more simpler way to create an Array is as shown in listing 3.2— Here the Array companion object has a method called apply (companion object and apply here is similar to a static method on class Array)

8. Use lists

  • A functional programming paradigm is “Methods should not have side effects. A method should compute and return a value”
  • Arrays are mutable objects — Although, length of an array cannot be changes after initialization although, the value itself can be changed.
  • Scala’s List — An immutable sequence of object that shares the same type. Nil is a shorthand way to initiate an empty list.
  • When a method is called on List — it creates and returns a new list with the new value. List has ‘:::’ method for concatenation.
Lists are immutable
  • List method ‘::’ pronounced ‘cons’ prepends element to the beginning of the list. Eg: 1::List(2,3)
  • List method ‘:+’ appends to a list but the time to append grows linearly with list size whereas cons take constant time. To efficiently append, either use ListBuffer, a mutable list and call toList on it or prepend and call reverse.
  • If a method ends with a ‘:’ it is invoked on the right operand.
Right operand invocation

9. Use Tuples

  • Container object tuple are immutable but can contain different types of elements, thus useful in cases like to return multiple objects from a method.
Creating and using a tuple of type Tuple2[Int, String]
  • The actual tuple type contains the number of elements and its type. The type of (‘u’, ‘r’, “the”, 1, 4, “me”) is Tuple6[Char, Char, String, Int, Int, String]. Although conceptually you could create tuples of any length, currently the Scala library only defines them up to Tuple22.
Tuple22 and Tuple23

10. Use Sets and Maps

  • Scala aims to help one take advantage of both functional and imperative styles and its collection libraries make a point to differentiate between mutable and immutable collections.
  • For sets and maps, Scala models mutability in the class hierarchy. It contains a base trait(similar to java interface) for sets, and two sub traits for mutable and immutable. In Scala, one“extend” or “mix in” traits.
Scala Set with same trait name but different packages
  • When you use the + method in a immutable set, it behaves similar to List creating a new Set with the appended element, whereas a mutable sets actually appends it. To create a mutable set, import the package for mutable set.
  • Immutable sets needs to be assigned to a var if they are going to be mutated as immutable Set is going to return a new object. On the contrary, mutable sets can be assigned to a val.

Maps

  • Maps has its own class hierarchy traits very similar to Set
  • In the example above, invoking the -> method on any object (implicit conversion) returns a two element tuple which is passed as an argument to += method of the Map.
  • An explicit type parameterization is required if you are creating an empty Map with () as in Listing 3.7

11. Learn to recognize the functional style

  • First step is to recognize the difference between the two styles in code.
  • Telltale sign 1: Code contains any vars, it is probably imperative style.
  • Telltale sign 2: A function with side effects is that its return type is Unit.
Imperative with vars in it
More functional implementation
  • Still has side effects as it returns Unit and printing something within.
  • A more functional approach is to define a method that formats the passed args for printing as follows
  • The mkString method, which you can call on any iterable collection (including arrays, lists, sets, and maps), returns a string consisting of the result of calling toString on each element, separated by the passed string
  • Preferring methods without side effects encourages you to design programs where side-effecting code is minimized thus, making testing much easier.
  • Scala is a hybrid imperative / functional language.

12. Read lines from a file

  • Source.fromFile(args(0)) attempts to open the file and returns a Source object.
  • getLines method returns an Iterator[String]. Once iterated through the iterator, it is spent and cannot be iterated again.
Find the longest line
  • reduceLeft applied the passed function to the first 2 elements in lines, then applies the result to the next element in the lines thus passing the current longest line to the next element and compare. reduceLeft will return the result of after the last element.
A more functional approach to print the padded line length with | as shown below
Print padded line length followed by | and the line itself.

Conclusion

Future gists will introduce more topics in depth.

--

--