# Understanding traits

*A brief introduction to traits*

Consider the following example in Java. Suppose we have an interface `Base`

and two interfaces `A`

and `B`

that extend `Base`

, each with a method `m()`

.

```
public interface Base {
default void m() {
System.out.println("Hello from Base");
}
}
interface A extends Base {
default void m() {
System. . . .
```

# The flatMap operation

*A brief intro to the flatMap operation*

The use case for `flatMap`

is when one wishes to compose the `map`

and `flatten`

operations, in that order.

```
val a = List(List(1, 2), List(3, 4))
val b = a.map((x: List[Int]) => x.map(_ * 2))
val c = b.flatten
```

`c`

will have the value `List(2,4,6,8)`

.

Due to its frequency of use, there is a built-in function in Scala that . . .

# The flatten operation

*A brief intro to the flatten operation*

We have a list of lists.

```
val a = List(List(1,2),List(3,4),List(5,6))
```

We want to concatenate those lists into a single list.

We can accomplish this using a `foldLeft`

pattern.

```
def f(a: List[List[Int]]): List[Int] = a.foldLeft(List[Int]())((flat,x)=> flat ++ x)
```

Note that `List[Int]()`

represents an empty list. . . .

# Mapping

*A brief intro to the map operation*

We have some collection. A list, say.

```
val a = List(1,2,3)
```

We have a function, `f`

.

```
def f(a: Int): Int = 2*a
```

We would like to evaluate `f`

at each element of `a`

and assign the return value to the corresponding position of a new list. `map`

accomplishes this.

```
val b = a.map(f)
```

The value of `b`

is `List(2,4,6)`

.

# Tail recursion

*A brief intro to tail recursion*

Suppose we would like to compute the sum of the elements of a list `List[Int]`

.

Consider the following recursive solution.

```
def sum[A](list: List[A]): Int = {
list match {
case Nil => 0
case x :: xs => x + sum(xs)
}
}
```

The following call to `sum`

will result in a `StackOverflowError`

.

`sum((0 to . . .`