日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

.toint

發布時間:2023/12/14 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .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] = Nonescala> 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?Try,?Success, 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.

總結

以上是生活随笔為你收集整理的.toint的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。