我想在SQL方法参数中隐式地将连接转换为JDBC连接的隐式连接参数。我有这段代码,它会抛出编译错误。
class JDBCConnection
class Connection(val connection: JDBCConnection)
object Connection {
implicit def Connection2JDBCConnection(connection: Connection) = connection.connection
}
object DB {
def withTransaction[A](block: (Connection => A)) = block(new Connection(new JDBCConnection))
}
object Main {
def SQL(query: String)(implicit connection: JDBCConnection) = println("SQL:" + query)
def main(args: Array[String]) = {
DB.withTransaction { implicit connection =>
SQL("Hello world")
}
}
}
Error:(20, 10) could not find implicit value for parameter connection: JDBCConnection
SQL("Hello world")
^
Error:(20, 10) not enough arguments for method SQL: (implicit connection: JDBCConnection)Unit.
Unspecified value parameter connection.
SQL("Hello world")我怎么才能解决这个问题?
我试图使用一个参数作为隐式,但仍然得到一个编译错误。
class Connection(val connection: JDBCConnection)
object Connection {
implicit def Connection2JDBCConnection(implicit connection: Connection) = connection.connection
}
Error:(20, 10) not enough arguments for method SQL: (implicit connection: JDBCConnection)Unit.
Unspecified value parameter connection.
SQL("Hello world")
^
Error:(20, 10) could not find implicit value for parameter connection: JDBCConnection
SQL("Hello world")
^发布于 2015-06-04 13:25:31
只有在显式使用Connection时,才会使用带有显式参数的隐式转换。如果您希望它隐式地工作,请让您的Connection2JDBCConnection接受一个implicit connection: Connection。
https://stackoverflow.com/questions/30645002
复制相似问题