01: Coding “Java way in Scala” Vs “Scala way in Scala”

Example #1: Read from a list & write to a list

Java Way in Scala

Output: List(Java Programming, Scala Programming, Ruby Programming)

Scala Way in Scala: Using the “map” functional combinator

Immutable code as shown below using the “map” function.

Scala Way in Scala: Using recursion

What does y :: ys mean?

It means head::tail. The head of the list is bound to “y”, and the rest (i.e. the tail) is bound to “ys”.

Example #2: Aggregate a list of values

Java Way by mutating state

Scala Way in Scala using the “foldLeft” functional combinator

Example #3: Conditional Aggregates

Java Way

Output: ListBuffer(Person(5,2500000)) , ListBuffer(Person(20,9500000)) , ListBuffer(Person(25,4500000))

Scala Way in Scala using case statements for the conditions & immutable List

Output:

Case class implicit copy method

When you create a case class in Scala, a copy method is generated for your case class. What does this copy method do?

Copy method lets you copy an object, where a ‘copy’ is different from a clone as you can change fields as desired during the copying process. The copy method is important in functional programming, where values (val) are immutable.

Scala’s ‘::’ operator, how does it work?

The operator :: is a function on a List class. So, “person :: stats.underTen” means

adding a person to a list named “underTen”, which is in the case class “SalaryByExperienceTotals”.

E.g. Foo(10) :: List(Foo(2)) means

E.g. In 1 + 2, “+” is a function on the object Int.


Java Interview FAQs

800+ Java Interview Q&As

Top