Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala中的字符串到Int_Scala - Fatal编程技术网

Scala中的字符串到Int

Scala中的字符串到Int,scala,Scala,假设我需要在Scala中将字符串转换为Int。如果字符串不是数字,我希望返回None,而不是抛出异常 scala> val zero = "0" zero: String = 0 scala> val foo = "foo" foo: String = foo scala> scala.util.Try(zero.toInt) res5: scala.util.Try[Int] = Success(0) scala> scala.util.Try(foo.toInt

假设我需要在Scala中将字符串转换为Int。如果字符串不是数字,我希望返回
None
,而不是抛出异常

scala> val zero = "0"
zero: String = 0

scala> val foo = "foo"
foo: String = foo

scala> scala.util.Try(zero.toInt)
res5: scala.util.Try[Int] = Success(0)

scala> scala.util.Try(foo.toInt)
res6: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "foo")
我发现如下

def toMaybeInt(s:字符串)={ 导入scala.util.control.Exception_ 捕获(classOf[NumberFormatException])选择s.toInt }
这有意义吗?您会更改/改进它吗?

对于可能引发异常的计算,我会使用
scala.util.Try
返回
Success
Failure

scala> val zero = "0"
zero: String = 0

scala> val foo = "foo"
foo: String = foo

scala> scala.util.Try(zero.toInt)
res5: scala.util.Try[Int] = Success(0)

scala> scala.util.Try(foo.toInt)
res6: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "foo")
因此,
toMaybeInt(s:String)
变成:

def toMaybeInt(s:String) = {
  scala.util.Try(s.toInt)
}

对于可能引发异常的计算,我会使用
scala.util.Try
返回
Success
Failure

scala> val zero = "0"
zero: String = 0

scala> val foo = "foo"
foo: String = foo

scala> scala.util.Try(zero.toInt)
res5: scala.util.Try[Int] = Success(0)

scala> scala.util.Try(foo.toInt)
res6: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "foo")
因此,
toMaybeInt(s:String)
变成:

def toMaybeInt(s:String) = {
  scala.util.Try(s.toInt)
}

为了在任何情况下获得一个选项,无论由于数字畸形可能出现的异常

import scala.util.Try

def toOptInt(s:String) = Try(s.toInt) toOption
然后

此外,考虑

implicit class convertToOptInt(val s: String) extends AnyVal {
  def toOptInt() = Try(s.toInt) toOption
}
因此


为了在任何情况下获得一个选项,无论由于数字畸形可能出现的异常

import scala.util.Try

def toOptInt(s:String) = Try(s.toInt) toOption
然后

此外,考虑

implicit class convertToOptInt(val s: String) extends AnyVal {
  def toOptInt() = Try(s.toInt) toOption
}
因此


谢谢,但我现在需要返回
Option
。@Michael使用
toOption
Catch[+T].toOption
scala.util.Try(“0.toInt”).toOption
或类似的
scala.util.Try(“foo.toInt”)。toOption
将返回
一些(0)
。谢谢,但我现在需要返回
选项
。@Michael Use
toOption
捕获[+T]。toOption?
scala.util.Try(“0.toInt”).toOption
或类似的
scala.util.Try(“foo.toInt”)。toOption
将返回
一些(0)
。除了使用
Try
(@brian's answer),我会将方法命名为
toIntOption
,以更符合标准Scala名称。除了使用
Try
(@brian's answer),我会将方法命名为
toIntOption
,以更符合标准Scala名称。