如何对隐式参数应用隐式转换?

时间:2015-06-04 13:23:00

标签: scala implicit

我想在SQL方法参数中隐式地将Connection转换为JDBC Connection以获取隐式连接参数。我有这个代码,它会抛出编译错误。

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")
         ^

1 个答案:

答案 0 :(得分:1)

只有在显式使用Connection时才会使用带有显式参数的隐式转换。如果您希望隐式使用它,请让Connection2JDBCConnection取一个implicit connection: Connection