I expect the code below to print out 1
and 2
. But I get default
and default
. When I explicitly forward (?) the implicit value using the commented out code, I see the desired output. Can anyone explain how this works? Is what I'm trying impossible? I'm totally new to Scala. What should I read to understand this in depth?
case class Context(id: Option[String])
object Context {
implicit val context = Context(Some("default"))
}
class ToolBuilder (id: String) {
implicit val context = Context(Some(id))
def extract() = ToolCreatorA.create()
}
case class ToolCreatorA(id: String)
object ToolCreatorA {
def create() = ToolCreator.create()
//def create()(implicit context: Context) = ToolCreator.create()
object ToolCreator {
def create()(implicit context: Context) = context.id.getOrElse("null")
}
}
object Main {
def main(args: Array[String]): Unit = {
println(new ToolBuilder("1").extract())
println(new ToolBuilder("2").extract())
}
}