Why does scala :_* for expanding the list of Seq arguments in variable length in this case not work?
and how to fix it elegantly?
import java.sql.Connection import scalikejdbc.ConnectionPool import anorm.{SQL, SqlQuery, SqlRow, Row} object AnormExample extends App { Class.forName("org.hsqldb.jdbc.JDBCDriver") ConnectionPool.singleton("jdbc:hsqldb:mem:hsqldb:WithAnorm", "", "") implicit val conn: Connection = ConnectionPool.borrow() // this works SQL("insert into emp (id, name) values ({id}, {name})").onParams(3, "name3").executeUpdate() // this does not compile val row = Seq(4, "name4") SQL("insert into emp (id, name) values ({id}, {name})").onParams(row:_*).executeUpdate() // david }
Error:
scala: type mismatch; found : Seq[Any] required: Seq[anorm.ParameterValue[?]] SQL("insert into emp (id, name) values ({id}, {name})").onParams(row:_*).executeUpdate() // david
ps:
<dependency> <groupId>play</groupId> <artifactId>anorm_2.10</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>com.github.seratch</groupId> <artifactId>scalikejdbc_2.10</artifactId> <version>1.5.1</version> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.2.9</version> </dependency>
any elegant solution?
Update
based on the answer from senia, this solves the problem:
def toParameterValueSet(seq: Seq[Any]) = seq.map(v => v: anorm.ParameterValue[_]) val row = Seq(5, "name5") SQL("insert into emp (id, name) values ({id}, {name})").onParams(toParameterValue(row):_*).executeUpdate()
Is there a way to remove the need to declare / use toParameterValueSet?
(for example, to tell scala to use implicit conversion when automatically expanding :_* )
Update
a little more compact:
implicit def toParameterValueSet(seq: Seq[Any]): Seq[anorm.ParameterValue[_]] = seq.map(v => v: anorm.ParameterValue[_]) val row = Seq(5, "name5") SQL("insert into emp (id, name) values ({id}, {name})").onParams(row:_*).executeUpdate()
@Typesafe command: can you add an acrom SQL parameter to take a series of values? (use: _ * instead) (I agree that using named parameters is preferable, but it is sometimes useful to have unnamed parameters)