|
| 1 | +import Predef.{any2stringadd => _, _} |
| 2 | +object augments { |
| 3 | + |
| 4 | +// Simple extension methods |
| 5 | + |
| 6 | + case class Circle(x: Double, y: Double, radius: Double) |
| 7 | + |
| 8 | + augment Circle { |
| 9 | + def circumference = this.radius * math.Pi * 2 |
| 10 | + } |
| 11 | + |
| 12 | +// Trait implementations |
| 13 | + |
| 14 | + trait HasArea { |
| 15 | + def area: Double |
| 16 | + } |
| 17 | + |
| 18 | + augment Circle extends HasArea { |
| 19 | + def area = this.radius * this.radius * math.Pi |
| 20 | + } |
| 21 | + |
| 22 | +// Generic trait implementations |
| 23 | + |
| 24 | + augment List[type T] { |
| 25 | + def second = this.tail.head |
| 26 | + } |
| 27 | + |
| 28 | +// Specific trait implementations |
| 29 | + |
| 30 | + augment List[Int] { |
| 31 | + def maxx = (0 /: this)(_ `max` _) |
| 32 | + } |
| 33 | + |
| 34 | + augment Array[Int] { |
| 35 | + def maxx = (0 /: this)(_ `max` _) |
| 36 | + } |
| 37 | + |
| 38 | +// Conditional extension methods |
| 39 | + |
| 40 | + case class Rectangle[T](x: T, y: T, width: T, height: T) |
| 41 | + |
| 42 | + trait Eql[T] { |
| 43 | + def eql (x: T, y: T): Boolean |
| 44 | + } |
| 45 | + |
| 46 | + augment Rectangle[type T: Eql] { |
| 47 | + def isSquare: Boolean = implicitly[Eql[T]].eql(this.width, this.height) |
| 48 | + } |
| 49 | + |
| 50 | + augment Rectangle[type T](implicit ev: Eql[T]) { |
| 51 | + def isNotSquare: Boolean = !implicitly[Eql[T]].eql(this.width, this.height) |
| 52 | + } |
| 53 | + |
| 54 | +// Simple generic augments |
| 55 | + |
| 56 | + augment (type T) { |
| 57 | + def ~[U](that: U): (T, U) = (this, that) |
| 58 | + } |
| 59 | + |
| 60 | +// Conditional generic augments |
| 61 | + |
| 62 | + trait HasEql[T] { |
| 63 | + def === (that: T): Boolean |
| 64 | + } |
| 65 | + |
| 66 | + augment eqlToHasEql @ (type T: Eql) extends HasEql[T] { |
| 67 | + def === (that: T): Boolean = implicitly[Eql[T]].eql(this, that) |
| 68 | + } |
| 69 | + |
| 70 | + augment (type T)(implicit ev: Eql[T]) { |
| 71 | + def ==== (that: T): Boolean = implicitly[Eql[T]].eql(this, that) |
| 72 | + } |
| 73 | + |
| 74 | + augment Rectangle[type T: Eql] extends HasEql[Rectangle[T]] { |
| 75 | + def === (that: Rectangle[T]) = |
| 76 | + this.x === that.x && |
| 77 | + this.y === that.y && |
| 78 | + this.width == that.width && |
| 79 | + this.height == that.height |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +object augments2 { |
| 84 | + import augments.{Eql, eqlToHasEql} |
| 85 | + // Nested generic arguments |
| 86 | + |
| 87 | + augment flatLists @ List[List[type U]] { |
| 88 | + def flattened: List[U] = (this :\ (Nil: List[U]))(_ ++ _) |
| 89 | + } |
| 90 | + |
| 91 | + augment samePairs @ (type T: Eql, T) { |
| 92 | + def isSame = this._1 === this._2 |
| 93 | + } |
| 94 | + |
| 95 | +} |
0 commit comments