I've recently started playing with Scala (2.8) and noticed the I can write the following code (in the Scala Interpreter):
scala> var x : Unit = 10 x : Unit = ()
It's not obvious what's going on there. I really didn't expect to see any implicit conversion to Unit.
Type Casting in Scala is done using the asInstanceOf[] method. This perspective is required in manifesting beans from an application context file. It is also used to cast numeric types. It can even be applied in complex codes like communicating with Java and sending it an array of Object instances.
Java int can be converted to long in two simple ways: This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.
def cast(number: Any): Long = number match { case n: RichLong => n. toLong case x => throw new IllegalArgumentException(s"$x is not a number.") } It might also be possible to add a case for matching a String in numeric format if you wanted to cater for that possibility. Updated for Scala 2.11.
In Scala, Long is a 64-bit signed integer, which is equivalent to Java's long primitive type. The *(x: Long) method is utilized to return the product of the specified Long value and Long value. Returns – Returns the product of this value and x.
See section "6.26.1 Value Conversions" in the Scala Language Specification version 2.8:
...
Value Discarding. If e
has some value type and the expected type is Unit, e
is converted to the expected type by embedding it in the term { e; () }
.
...
Anything can be converted to Unit. This is mostly necessary to support side-effecting methods which nonetheless return values, but where the return value is often ignored. For instance
import java.util.{List =>JList} def remove2[A](foo: JList[A], a1:A, a2:A):Unit = { foo.remove(a1) foo.remove(a2) //if you couldn't convert the (usually pointless) return value of remove to Unit, this wouldn't type }
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