Cuper Hector
Cuper Hector

Reputation: 856

How to do simple type cast in Scala?

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?

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

Upvotes: 23

Views: 25820

Answers (2)

Kevin Wright
Kevin Wright

Reputation: 49705

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

val b = 23 : Byte

Upvotes: 13

Landei
Landei

Reputation: 54584

1.5f.toInt

//--> res0: Int = 1

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

Upvotes: 44

Related Questions