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 } }
The Karp-Rabin Algorithm.
String Matching Algorithm is also called "String Searching Algorithm." This is a vital class of string algorithm is declared as "this is the method to find a place where one is several strings are found within the larger string." Given a text array, T [1.....n], of n character and a pattern array, P [1......
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
The string matching problem is this: given a smaller string P (the pattern) that we want to find occurrences of in T . If P occurs in T at shift i then P[j] = T[i+j] for all valid indices i of P . For example, in the string "ABABABAC", the pattern string "BAB" occurs at shifts 1 and 3.
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.
Here is an alternate way. Store all the mappings in a map and then use collectFirst
method to find the match. Type signature of collectFirst
is:
def TraversableOnce[A].collectFirst[B](pf: PartialFunction[A, B]): Option[B]
Usage:
scala> val urlMappings = Map("jdbc:mysql:" -> "com.mysql.jdbc.Driver", "jdbc:postgresql:" -> "org.postgresql.Driver") urlMappings: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(jdbc:mysql: -> com.mysql.jdbc.Drive r, jdbc:postgresql: -> org.postgresql.Driver) scala> val url = "jdbc:mysql:somestuff" url: java.lang.String = jdbc:mysql:somestuff scala> urlMappings collectFirst { case(k, v) if url startsWith k => v } res1: Option[java.lang.String] = Some(com.mysql.jdbc.Driver)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With