字符串模式匹配最佳实践
以下是不起作用的代码,但它描述了我想要做的事情。
您能推荐解决这个问题的最佳方法吗?
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
}
}
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 Scala 2.13 开始,可以通过 取消应用字符串插值器:
然后在我们的例子中,只需使用
Map
将提取的值(sql 方言)映射到适当的驱动程序即可:如果您期望输入格式错误,您还可以使用匹配语句:
Starting
Scala 2.13
, it's possible to pattern match aString
s by unapplying a string interpolator:Then in our case, it's just a matter of mapping the extracted value (the sql dialect) to the appropriate driver using a
Map
:If you are expecting malformed inputs, you can also use a match statement:
这是另一种方法。将所有映射存储在映射中,然后使用
collectFirst
方法查找匹配项。collectFirst
的类型签名是:用法:
Here is an alternate way. Store all the mappings in a map and then use
collectFirst
method to find the match. Type signature ofcollectFirst
is:Usage:
在语法方面,您可以稍微修改一下 case 语句:
这只是将值
url
绑定到模式表达式(也是url
)并添加一个保护表达与测试。这应该会使代码编译。为了让它更像 scala,你可以返回一个 Option[String] (我删除了几个子句,因为它只是为了说明):
除非你想管理异常。
In terms of syntax, you can modify just a tiny bit you case statements:
This simply binds the value
url
to 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.