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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I tried to use a parameter as an implicit but still get a compilation error
Looking at your code, do you need to import the implicit method? Also, what's the definition of DB.withTransaction?
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
The problem is just that the implicit method is not in scope. If I add import Connection._ just before Main then it works.
Thank you, it works!!! You could not give me a link where I could learn more about the scope?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.