如何在 Scala 中进行简单的类型转换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3819826/
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 02:27:18  来源:igfitidea点击:

How to do simple type cast in Scala?

scalatypescasting

提问by Cuper Hector

This should be a silly question.

这应该是一个愚蠢的问题。

scala> val aFloat = 1.5f
aFloat: Float = 1.5

How to cast aFloat to an Int in a simple way?

如何以简单的方式将 aFloat 转换为 Int?

I already know to use a.asInstanceOf[Int]. But it needs too much keystrokes.

我已经知道使用a.asInstanceOf[Int]. 但它需要太多的击键。

回答by Landei

1.5f.toInt

//--> res0: Int = 1

You have toDouble, toFloat, toInt and toLong on all number types.

您必须对所有数字类型进行 toDouble、toFloat、toInt 和 toLong。

回答by Kevin Wright

as well as the toFloat, toInt, etc. methods, you can also use type ascription in some cases:

除了 toFloat、toInt 等方法,你还可以在某些情况下使用类型归属:

val b = 23 : Byte