我如何在Scala中投射?

例如,假设我有

val myDouble = 25.7 val myInt = 5 

我将如何做类似的事情

 val divide = (Int) (myDouble / myInt) 

你可以做(myDouble/myInt).toInt 。 你也可以做到toFloattoFloattoFloat

我的首选方法是添加舍入方法,以减less任何潜在的转换行为的惊喜:

 val divide = (myDouble/myInt).ceil.toInt 

要么

 val divide = (myDouble/myInt).floor.toInt 

或者你可以做…

  scala> val myDouble = 25.7 myDouble: Double = 25.7 scala> val myInt = 5 myInt: Int = 5 scala> val divide = (myDouble / myInt).asInstanceOf[Int] divide: Int = 5