gpt4 book ai didi

java - 在 Scala 中将字符串转换为整数的最简洁方法?

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:27 25 4
gpt4 key购买 nike

<分区>

在Java中,我可以使用如下两条语句将字符串转换为整数,它能够处理异常:

// we have some string s = "abc"
int num = 0;
try{ num = Integer.parseInt(s); } catch (NumberFormatException ex) {}

然而,我在 Scala 中找到的方法总是使用 try-catch/match-getOrElse 方法,如下所示,它由几行代码组成,看起来有点冗长。

// First we have to define a method called "toInt" somewhere else
def toInt(s: String): Option[Int] = {
try{
Some(s.toInt)
} catch {
case e: NumberFormatException => None
}
}

// Then I can do the real conversion
val num = toInt(s).getOrElse(0)

这是在 Scala 中将字符串转换为整数的唯一方法(能够处理异常)还是有更简洁的方法?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com