Regex.MatchData returning null: why not Option[String]?

人盡茶涼 提交于 2019-12-23 07:39:00

问题


Is there any particular reason why Regex.MatchData.group(i: Int): java.lang.String returns null rather than Option[String]?

Is there a "Scala Way" to handle nulls in Scala?


回答1:


It returns null because it is a shallow interface over the Java library. I think it sucks too, and I have been bitten by it.

If you get a value that may be null, you can write Option(value) on Scala 2.8 and it will become either None or Some(value). That doesn't work with pattern matching, but you can write your own extractor for that:

object Optional {
  def unapply[T](a: T) = if (null == a) Some(None) else Some(Some(a))
}

Examples:

scala> val a:String = null
a: String = null

scala> a match {
     | case Optional(None) => println("Got none")
     | case Optional(Some(value)) => println("Got "+value)
     | }
Got none

scala> val a = "string"
a: java.lang.String = string

scala> a match {
     | case Optional(None) => println("Got none")
     | case Optional(Some(value)) => println("Got "+value)
     | }
Got string

scala> val a = "5"
a: java.lang.String = 5

scala> a match {
     | case Optional(None) => println("Got none")
     | case Optional(Some(value)) => println("Got "+value.toInt)
     | }
Got 5


来源:https://stackoverflow.com/questions/1842925/regex-matchdata-returning-null-why-not-optionstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!