Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do simple type cast in Scala?

Tags:

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.

like image 617
Cuper Hector Avatar asked Sep 29 '10 08:09

Cuper Hector


People also ask

What is some () in Scala?

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.

What is type casting with example?

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.

What is a cast data type?

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.


2 Answers

1.5f.toInt  //--> res0: Int = 1 

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

like image 118
Landei Avatar answered Oct 31 '22 09:10

Landei


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

val b = 23 : Byte 
like image 36
Kevin Wright Avatar answered Oct 31 '22 09:10

Kevin Wright