0

I want to implicitly convert Connection to JDBC Connection for implicit connection parameter in SQL method parameter. I have this code, which throw compilation error.

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

How can I fix this?

I tried to use a parameter as an implicit but still get a compilation error

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")
         ^
Sergey
  • 133
  • 1
  • 8

1 Answers1

1

An implicit conversion that takes an explicit argument will only be used if the Connection is used explicitly. If you want it to work implicitly, make your Connection2JDBCConnection take an implicit connection: Connection.

lmm
  • 17,386
  • 3
  • 26
  • 37
  • I tried to use a parameter as an implicit but still get a compilation error – Sergey Jun 04 '15 at 13:29
  • Looking at your code, do you need to import the implicit method? Also, what's the definition of `DB.withTransaction`? – lmm Jun 04 '15 at 13:31
  • I have all the code in a single file, all of the code is given at the beginning of the question. I want to wrap a standard JDBCConnection still be able to implicitly convert it to a standard JDBCConnection – Sergey Jun 04 '15 at 13:33
  • The problem is just that the implicit method is not in scope. If I add `import Connection._` just before `Main` then it works. – lmm Jun 04 '15 at 13:38
  • Thank you, it works!!! You could not give me a link where I could learn more about the scope? – Sergey Jun 04 '15 at 13:41
  • See "Where do implicits come from?" in http://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits/5598107#5598107 – lmm Jun 04 '15 at 13:47