Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Trait in Scala

Trait in Scala

2014/05/09 Livesense SICP倶楽部LT大会にて
ScalaのTraitについての解説

Livesense Inc.

May 15, 2014
Tweet

More Decks by Livesense Inc.

Other Decks in Programming

Transcript

  1. w JOUFSGBDFͷσϑΥϧτ࣮૷ w ϥϜμࣜ w ߴ֊ؔ਺ w ܕਪ࿦ͷڧԽ w ฒྻੑͷڧԽʢฒྻίϨΫγϣϯɺ$PNQMFUF'VUVSFʣ

    w ஗ԆධՁ w 4USFBN w 0QUJPOBM w FUD IUUQXXXJOGPRDPNKQBSUJDMFTKBWBWTTDBMB IUUQOFXTNZOBWJKQTQFDJBMKBWB
  2. trait A { def f() // ந৅ϝιου } ! trait

    B { def foo() = println("foo") } ! trait C { def bar() = println("bar") } ! class D extends A with B with C { def f() = foo() // ந৅ϝιουΛ࣮૷ˍτϨΠτBͷfooΛݺͼग़͠ override def bar() = { // τϨΠτCͷbarϝιουΛoverride super.bar() // τϨΠτCͷbarϝιουΛݺͼग़͠ println("BAR") } }
  3. class Japanese ! trait Kansai ! trait Kanto ! val

    me = new Japanese with Kansai with Kanto
  4. class Animal ! trait HasLegs extends Animal ! trait FourLegged

    extends HasLegs ! trait Furry extends Animal ! class Cat extends Animal with Furry with FourLegged
  5. 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) } }
  6. 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 ʰ4DBMBεέʔϥϒϧϓϩάϥϛϯάʱষΑΓ
  7. trait Executor { def execute(): Unit } ! trait LoggableExecutor

    extends Executor { def log(() => Unit):Unit = … abstract override def execute(): Unit { log { super.execute } } } ! class SomeExecutor extends Executor { def execute(): Unit = … } ! val e = new SomeExecutor with LoggableExecutor e.execute
  8. 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
  9. 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) } }
  10. 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)