Regex.MatchData 返回 null:为什么不是 Option[String]? [英] Regex.MatchData returning null: why not Option[String]?

查看:60
本文介绍了Regex.MatchData 返回 null:为什么不是 Option[String]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Regex.MatchData.group(i: Int): java.lang.String 返回 null 而不是 Option[String] 有什么特别的原因吗?

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

是否有Scala 方式"来处理 Scala 中的空值?

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

推荐答案

它返回 null,因为它是 Java 库上的一个浅接口.我也觉得它很烂,我被它咬过.

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.

如果你得到一个可能为空的值,你可以在 Scala 2.8 上编写 Option(value) ,它会变成 NoneSome(value)).这不适用于模式匹配,但您可以为此编写自己的提取器:

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

示例:

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

这篇关于Regex.MatchData 返回 null:为什么不是 Option[String]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆