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.
Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.
Typecasting, or type conversion, is a method of changing an entity from one data type to another. It is used in computer programming to ensure variables are correctly processed by a function. An example of typecasting is converting an integer to a string.
A data type that can be changed to another data type is castable from the source data type to the target data type. The casting of one data type to another can occur implicitly or explicitly. The cast functions or CAST specification (see CAST specification) can be used to explicitly change a data type.
1.5f.toInt //--> res0: Int = 1
You have toDouble, toFloat, toInt and toLong on all number types.
as well as the toFloat, toInt, etc. methods, you can also use type ascription in some cases:
val b = 23 : Byte
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With