Skip to content

Instantly share code, notes, and snippets.

@doxxx
Last active December 16, 2015 15:59
Show Gist options
  • Select an option

  • Save doxxx/5459937 to your computer and use it in GitHub Desktop.

Select an option

Save doxxx/5459937 to your computer and use it in GitHub Desktop.
trait FreshProducer[T] {
def fresh(): T
}
class Foo {
override def toString = "Foo!"
}
implicit object FooProducer extends FreshProducer[Foo] {
def fresh() = new Foo
}
class Term[T](implicit producer: FreshProducer[T]) {
def doStuff {
val x: T = producer.fresh()
}
lazy val value = producer.fresh()
}
val t = new Term[Foo]
println(t.value)
@doxxx
Copy link
Copy Markdown
Author

doxxx commented Apr 25, 2013

Technically, object Foo doesn't need to be called Foo since all Term needs is an object that implements the producer trait.

@doxxx
Copy link
Copy Markdown
Author

doxxx commented Apr 25, 2013

You can run this gist using "scala gistfile1.scala".

@elecnix
Copy link
Copy Markdown

elecnix commented Apr 26, 2013

So the "trick" here is to declare a Term[T] that also needs a FreshProducer[T], where T is the same for both. But why the implicit? And the lazy val value is just for illustration, I suppose, since there's already doStuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment