【发布时间】:2015-05-11 17:29:12
【问题描述】:
我从这个Link看到了下面的代码
abstract class SessionFactory {
protected[squery] def createConnection(): Connection
def createSession(): Session = new Session(this)
def withSession[T](f: Session => T): T = {
val s = createSession()
try { f(s) } finally s.close()
}
def withSession[T](f: => T): T =
withSession { s: Session => SessionFactory.dyn.withValue(s)(f) }
}
object SessionFactory {
private val dyn = new DynamicVariable[Session](null)
implicit def getThreadSession: Session = {
val s = dyn.value
if(s eq null)
throw new SQLException("No implicit thread session available; getThreadSession() can only be used within a withSession block")
else s
}
}
我不知道def withSession[T](f: => T): T如何获得s:Session的值,所以我尝试在一个简单的sn-p中重现implicit的这种用法:
class printTest {
def printWithParameter(s:String) = println(s)
def printWithImplicit = printWithParameter(s:String)
}
object printTest {
implicit val sp:String = "implicit value"
implicit def getString:String = "implicit def"
}
val pt = new printTest()
pt.printWithImplicit
但是printTest 不起作用,编译器说:
Error:(3, 47) not found: value s
def printWithImplicit = printWithParameter(s:String)
^
有人对此有想法吗?
【问题讨论】: