Atif Shahzad - 3 months ago 12

Scala Question

I have a code written by some one else. Can you help me to understand this piece of code?

`def sameCodeForTwoYears(list: List[(LocalDate, String)]): List[(LocalDate, String)] = {`

list match {

case x :: Nil => List.empty

case x :: xs => if (xs.head._1.minusYears(2).isAfter(x._1) && x._2 == xs.head._2) {

List(x, xs.head)

} else sameCodeForTwoYears(xs)

case Nil => List.empty

}

}

Answer

Scalas `List[+T]`

is an abstract class, implemented by two concrete classes:

`Nil`

- Representing an empty list`Cons`

(`::`

) - Represents a linked list with a`head`

of type`T`

and a`tail`

of type`List[+T]`

.

The pattern match you see here basically represents these two constructs. Let's do a by case analysis:

```
case x :: Nil => List.empty
```

Means "if `head`

is non empty and `tail`

is an empty list, return an `List.empty`

", which returns an empty list.

```
case x :: xs => if (xs.head._1.minusYears(2).isAfter(x._1) && x._2 == xs.head._2) {
List(x, xs.head)
```

Means "if both `head`

and `tail`

are non-empty". The predicates following the match basically look into the tuple stored inside the `List[(LocalDateTime, String)]`

where `_1`

represents the first element and `_2`

represents the second element. We dig a little deeper into the meaning if the condition:

```
xs.head._1.minusYears(2).isAfter(x._1)
```

Means "take the first element from tail (`xs`

, it's head), look into the first element in the tuple and subtract it by 2 years. If the first element in `x`

s tuple (which is a `LocalDateTime`

) is after that time.

And

```
x._2 == xs.head._2
```

Means "look into the heads (`x`

) second element, which is a `String`

, and match it to the next element which is the tails (`xs`

) first element (`xs.head`

) and match both strings for equality.

Finally:

```
case Nil => List.empty
```

Means "if the list is empty", return an empty list.

Source (Stackoverflow)

Comments