String pattern matching best practice

Nikita Volkov picture Nikita Volkov · Oct 8, 2011 · Viewed 32.5k times · Source

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
  }
}

Answer

huynhjl picture huynhjl · Oct 8, 2011

In terms of syntax, you can modify just a tiny bit you case statements:

case url if url.startsWith("jdbc:mysql:") => "com.mysql.jdbc.Driver"

This simply binds the value url to the pattern expression (which is also url) 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):

def resolveDriver(url: String) = url match {
  case u if u.startsWith("jdbc:mysql:") => Some("com.mysql.jdbc.Driver")
  case u if u.startsWith("jdbc:postgresql:") => Some("org.postgresql.Driver")
  case _ => None
}

That is unless you want to manage exceptions.