scala 将任何字符串转换为 Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20006025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:51:15  来源:igfitidea点击:

Cast Any of String to Int

scala

提问by アレックス

I have a variable of type Anywith runtime type of Stringwhich I want to cast to Int:

我有一个类型Any为运行时类型的变量String,我想将其转换为Int

val a: Any = "123"

If I try to cast in to Int, I'll get an exception java.lang.ClassCastException:

如果我尝试转换为 Int,我会得到一个异常java.lang.ClassCastException

val b = a.asInstanceOf[Int]

How do I do that then?

那我该怎么做呢?

回答by 0__

Casting doesn't convertyour type, it simply tells the system that you think you are smart enough to know the proper type of an object. For example:

转换不会转换您的类型,它只是告诉系统您认为您足够聪明,可以知道对象的正确类型。例如:

trait Foo
case class Bar(i: Int) extends Foo

val f: Foo = Bar(33)
val b = f.asInstanceOf[Bar]  // phew, it works, it is indeed a Bar

What you are probably looking for is to convert a Stringto an Int:

您可能正在寻找的是将 a 转换String为 an Int

val a: Any = "123"
val b = a.asInstanceOf[String].toInt

Or, since you can call toStringon any object:

或者,因为您可以调用toString任何对象:

val b = a.toString.toInt

You can still get a runtime exception if the string is not a valid number, e.g.

如果字符串不是有效数字,您仍然可以获得运行时异常,例如

"foo".toInt  // boom!

回答by flavian

In general you steer clear of class casts and nested try catchblocks in Scala.

通常,您会避开try catchScala 中的类强制转换和嵌套块。

import scala.util.{ Try, Failure, Success };

val x: Any = 5;
val myInt = Try { x.toString.toInt) } getOrElse { 0 // or whatever}; // this is defaulting
val mySecondInt = Try { x.toString.toInt };
mySecondInt match {
   case Success(theactualInt) => // do stuff
   case Failure(e) => // log the exception etc.
}

回答by djcastr0

scala> val a:Any = "123"
a: Any = 123

scala> val b = a.toString.toInt
b: Int = 123