Following is the code that doesn’t work but it describes what I want to do.
Could you please recommend the best approach to this problem?
def resolveDriver(url: String) = {
url match {
case url.startsWith("jdbc:mysql:") => "com.mysql.jdbc.Driver"
case url.startsWith("jdbc:postgresql:") => "org.postgresql.Driver"
case url.startsWith("jdbc:h2:") => "org.h2.Driver"
case url.startsWith("jdbc:hsqldb:") => "org.hsqldb.jdbcDriver"
case _ => throw new IllegalArgumentException
}
}
In terms of syntax, you can modify just a tiny bit you case statements:
This simply binds the value
urlto the pattern expression (which is alsourl) and adds a guard expression with a test. That should make the code compile.To make it a little bit more scala-like, you can return an Option[String] (I removed a couple clause since it’s just for illustration):
That is unless you want to manage exceptions.