Scala Traits Flashcards

1
Q

Trait

Definition

A

Traits are used to share interfaces and fields between classes. They are similar to Java 8’s interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

Traits can contain:
* Abstract methods and fields
* Concrete methods and fields

trait HasLegs {
  def numLegs: Int
  def walk(): Unit
  def stop() = println("Stopped walking")
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Define a Trait

Write example

A

trait HairColor

Traits become especially useful as generic types and with abstract methods.
~~~
trait Iterator[A] {
def hasNext: Boolean
def next(): A
}
~~~

Extending the trait Iterator[A] requires a type A and implementations of the methods hasNext and next.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Use traits

Write example

A

Use the extends keyword to extend a trait. Then implement any abstract members of the trait using the override keyword

trait Iterator[A] {
  def hasNext: Boolean
  def next(): A
}

class IntIterator(to: Int) extends Iterator[Int] {
  private var current = 0
  override def hasNext: Boolean = current < to
  override def next(): Int = {
    if (hasNext) {
      val t = current
      current += 1
      t
    } else 0
  }
}

val iterator = new IntIterator(10)
iterator.next()  // returns 0
iterator.next()  // returns 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Subtyping

A

Where a given trait is required, a subtype of the trait can be used instead.

import scala.collection.mutable.ArrayBuffer

trait Pet {
  val name: String
}

class Cat(val name: String) extends Pet
class Dog(val name: String) extends Pet

val dog = new Dog("Harry")
val cat = new Cat("Sally")

val animals = ArrayBuffer.empty[Pet]
animals.append(dog)
animals.append(cat)
animals.foreach(pet => println(pet.name)) 
How well did you know this?
1
Not at all
2
3
4
5
Perfectly