.toint

Scala : How do I convert a String to Int in Scala?

Solution: Use ‘toInt’

If you need to convert a String to an Int in Scala, just use the toInt method, which is available on String objects, like this:

scala> val i = "1".toInt
i: Int = 1

As you can see, I just cast the string "1" to an Int object using the toInt method, which is available to any String.

However, beware that this can fail with a NumberFormatException just like it does in Java, like this:

 

scala> val i = "foo".toInt
java.lang.NumberFormatException: For input string: "foo"

so you’ll want to account for that in your code, such as with a try/catch statement.

A Java-like String to Int conversion function

The following functions show a couple of ways you can handle the exception that can be thrown in the string to int conversion process. This first example shows the “Java” way to write a String to Int conversion function:

def toInt(s: String): Int = {
  try {
    s.toInt
  } catch {
    case e: Exception => 0
  }
}

That function returns the correct int value if the string can be converted to an int (such as "42"), and returns 0 if the string is something else, like the string "foo".

A Scala “String to Int” conversion function that uses Option

A more "Scala like" way to write a string to int conversion function looks like this:

def toInt(s: String): Option[Int] = {
  try {
    Some(s.toInt)
  } catch {
    case e: Exception => None
  }
}

 

This function returns a Some(Int) if the string is successfully converted to an int, and a None if the string could not be converted to an integer. This function is shown in the following REPL examples:

scala> val x = toInt("foo")
x: Option[Int] = None

scala> val x = toInt("10")
x: Option[Int] = Some(10)

As I wrote in my book about Scala and functional programming, you can also write a Scala toInt function that uses TrySuccess, and Failure like this:

import scala.util.{Try, Success, Failure}
def makeInt(s: String): Try[Int] = Try(s.trim.toInt)

You can also return an Option like this:

import scala.util.control.Exception._
def makeInt(s: String): Option[Int] = allCatch.opt(s.toInt)

Please see my Scala Option/Some/None idiom tutorial for more ways to use these patterns, and to use the Option and Try results.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值