Defining a "with implicit context" construct in Scala

时间:2016-04-04 17:54:07

标签: scala implicit

Suppose I have an API set up to accept an implicit context.

def foo(i : Int)(implicit ctx : Context) : Int = ???
def bar(s : String)(implicit ctx : Context) : Int = ???

Applications might require multiple contexts. It's not always appropriate to just import of widely used value. But contexts are annoying to create, and require some cleanup when they will no longer be used. So, I want to define an API like this:

withContext( m : Mood, w : Weather ) {
  val f = foo(7)
  val b = bar("Boo!")
  f + b
}

Within my code block, an implicit context would be set. At the end, it would be cleaned up.

I thought this would be easy, but I've quickly confused myself.

I try something like

def withContext[R]( m : Mood, w : Weather )( op : Context => R ) : R = {
   implicit val context = FeelyContext(m,w)
   try op( context ) finally context.close()
}

but that doesn't work. I'd still need to write

withContext( m : Mood, w : Weather ) { context =>
  val f = foo(7)( context )
  val b = bar("Boo!")( context )
  f + b
}

which is not so convenient.

Is there a way to do this in ordinary scala? Would it need to be a macro trick, since implicit resolution happens at compile time?

Update: It occurs to me that it should work to write

withContext( m : Mood, w : Weather ) { implicit context =>
  val f = foo(7)
  val b = bar("Boo!")
  f + b
}

which is not so bad. Still, is there any way to do without the declaration of context entirely?

0 个答案:

没有答案