Scala Design Patterns.
上QQ阅读APP看书,第一时间看更新

Extending classes

It is possible for traits to extend classes. Let's have a look at the following example:

abstract class Connector {
def connect()
def close()
}

trait ConnectorWithHelper extends Connector {
def findDriver(): Unit = {
System.out.println("Find driver called.")
}
}

class PgSqlConnector extends ConnectorWithHelper {
override def connect(): Unit = {
System.out.println("Connected...")
}

override def close(): Unit = {
System.out.println("Closed...")
}
}

Here, as expected, PgSqlConnector will be obliged to implement the abstract class methods. As you can guess, we could have other traits that extend other classes and then we might want to mix them in. Scala, however, will put a limit in some cases, and we will see how it will affect us later in this chapter when we look at compositions.