DEV Community

loading...
Cover image for 5 Scala syntactic Tips&Tricks

5 Scala syntactic Tips&Tricks

Bartosz Gajda
Passionate and growth-minded Big Data Developer and Machine Learning enthusiast.
Originally published at bartoszgajda.com ・3 min read

Scala is quite a special language. Your initial lines of code, especially if you know Java, are quite simple. But, after digging deeper into all hidden super powers of the language, it’s easy to get totally lost. In this post, I will present you some of the coolest syntactic sugar that I have came across when reading Scala code and working through some of the tutorials found in the web. I hope it will help you with going from good to great, at Scala development. Enjoy!

#1 Calling single parameter methods

Methods with single parameters have can be called using very cool curly brace expression. But first, let’s say we have a Scala function like this:

def saySomething(sentence: String): String = "I say $sentence"

What you would typically would do to call that function is probably use standard parentheses and pass the argument:

val sentenceSaid = saySomething("it's sunny today")

This standard expression, can be changed to something really cool. We can call the function without parentheses, but use curly braces instead to create more advanced block of code that can do some operations, before actually calling a function.

val sentenceSaid2 = saySomething {
  // add some more expression
  "it's rainy today"
}

The code above will have exactly same effect as calling a method using parentheses, but you can add more expressions before actually calling a function.

#2 Single abstract method

Single abstract method is another cool trick if you have a trait that implements only one function. Let’s assume that the trait looks like this:

trait Action {
  def act(x: Int): Int
}

Typically, you would create a class the implements this trait, and then override the method with desired implementation, or implement an anonymous class like this:

val instance: Action = new Action {
  override def act(x: Int): Int = x % 2
}

What single abstract method does, it allows to reduce the anonymous class like above, to a lambda. This implementation would like like this:

val lambdaInstance: Action = (x: Int) => x % 2

The code above is looking much more concise and expressive, hence reducing the lines of code you have to write. Very cool stuff :) More can be found here.

#3 Multi word method naming

That one is actually very very cool to show off what Scala can do :) In standard naming convention, you probably start with lower case word and then start adding more specific words in uppercase to construct a name for a method. But there is a nicer way to do it. Let’s assume we have a method like this:

def engineHpToKw(horsepower: Int): Int = horsepower * 0.74

The method above is quite standard and non interesting at all. What interesting we can do, is write it’s name as a multi word, like this:

def `calculate engine kilowatts from horsepower`(horsepower: Int): Int = horsepower * 0.74

The one above looks very cool and can become very useful when it’s hard to find a concise name for a method. Note that the words are closed in back ticks (`), and not single quotes. Calling such method look like this:

val kw = `calculate engine kilowatts from horsepower` 120

#4 Infix types

Infix types can be very useful when working with generic in Scala language. Let’s say that we have a code like this:

class Composite[A, B]
val composite: Composite[Int, String] = ???

What infix types allow us to do, is to change the value composite above into something like this:

val composite: Int Composite String = ???

The latter is a bit more concise and keeps the meaning of the original expression. More can be found here.

#5 Sequences and operators

Last bit is probably more obvious than other ones. The Sequence class has quite a lot of cool operators that can speed up the work with collections. Let’s have a look then:

val letters = Set("A", "B", "C")

// Append element
val lettersPlusD= letters + "D" // letters = Set("A", "B", "C", "D")
// Remove element
val lettersMinusC = letters - "C" // letters = Set("A", "B", "D")

val lettersTwo = Seq("E", "F")

// Concatenate two sequences
val lettersCombined = letters ++ letters2 // Set("A", "B", "D", "E", "F")
// Prepend an element to sequence
val lettersCombinedWithG = "G" +: lettersCombined // Set("G", "A", "B", "D", "E", "F")
// Get intersection between two sequences
val commonLetters = letters & lettersCombinedWithG // Set("A", "B")
// Get difference between two sequences (elements in the first sequences that are missing in the second one)
val difference = letters &~ lettersCombinedWithG // Set("C")

More can be found here.

Summary

I hope you have found this post useful. If so, don’t hesitate to like or share this post. Additionally you can follow me on my social media if you fancy so :)

Discussion (0)