24. abstract class IntQueue {
def put(x: Int)
def get(): Int
}
!
import scala.collection.mutable.ArrayBuffer
class BasicIntQueue {
private val but = new ArrayBuffer[Int]
def put(x: Int) = but += x
def get() = but.remove(0)
}
!
trait Doubling extends IntQueue {
abstract override def put(x: Int) = {
super.put(2 * x)
}
}
!
trait Filtering extends IntQueue {
abstract override def put(x: Int) = {
super.put(x.abs)
}
}
25. val q1 = new BasicIntQueue
q1.put(10)
q1.get() // Int = 10
!
val q2 = new BasicIntQueue with Doubling
q2.put(10)
q2.get() // Int = 20
!
val q3 = new BasicIntQueue with Doubling with
Filtering
q3.put(-10)
q3.get() // Int = 20
〆Scalaスケ`ラブルプログラミング〇12嫗より
29. trait A {
def foo() = ^foo ̄
}
!
trait B {
def bar() = ^bar ̄
}
!
trait C {
this: A with B =>
def f() = foo + bar
}
!
val c = new C with A with B
c.f // String = foobar
32. class User
!
trait UserRepositoryComponent {
val repos: UserRepository
trait UserRepository {
def findById(id: Int): User
}
}
!
class UserService {
this: UserRepositoryComponent =>
def findById(id: Int): User = {
repos.findById(id)
}
}
33. trait MySQLUserRepositoryComponent
extends UserRepository Component {
val repos = new MySQLUserRepository
class MySQLUserRepository = {
def findById(id: Int): User = ´
}
}
!
val userService =
new UserService with MySQLUserRepositoryComponent
!
val user = userService.findById(1)