Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ohsitab/544143 to your computer and use it in GitHub Desktop.
Save ohsitab/544143 to your computer and use it in GitHub Desktop.
/*
implicit parameterを参照するには、コンパニオンオブジェクト内の定義を探す場合も、その定義位置より後でないとダメみたい。
以下のコードだと
error: could not find implicit value for evidence parameter of type RichGraphics.Drawer[MyLine]
g.draw(MyLine(10, 30, 50, 20))
というエラーになる。
new Frame { ... } の部分をコードの一番最後に移動すると、
うまく動くようになる。
*/
import swing._
import java.awt.Graphics2D
new Frame {
contents = new BorderPanel {
preferredSize = new Dimension(100, 100)
override def paintComponent(g:Graphics2D) {
implicit def enrichGraphics(g: Graphics2D) = new RichGraphics(g)
g.draw(MyLine(10, 30, 50, 20))
g.draw(MyRect(40, 40, 20, 20))
}
}
visible = true
}
case class MyLine(x1: Int, y1: Int, x2: Int, y2: Int)
case class MyRect(x: Int, y: Int, w: Int, h: Int)
object RichGraphics {
trait Drawer[T] {
def draw(g: Graphics2D, target: T)
}
implicit object myLineDrawer extends Drawer[MyLine] {
def draw(g: Graphics2D, t: MyLine) =
g.drawLine(t.x1, t.y1, t.x2, t.y2)
}
implicit object myRectDrawer extends Drawer[MyRect] {
def draw(g: Graphics2D, t: MyRect) =
g.drawRect(t.x, t.y, t.w, t.h)
}
}
class RichGraphics(g: Graphics2D) {
def draw[T: RichGraphics.Drawer](target: T) =
implicitly[RichGraphics.Drawer[T]].draw(g, target)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment