Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why can I convert Int to Unit?

Tags:

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.

like image 224
PGene Avatar asked Aug 18 '10 14:08

PGene


People also ask

How do you typecast in Scala?

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.

How do you type a long cast?

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.

How do you cast to long in Scala?

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.

How do you define a long Scala?

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.


2 Answers

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; () }.

...

like image 173
mkneissl Avatar answered Oct 18 '22 16:10

mkneissl


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 } 
like image 41
Dave Griffith Avatar answered Oct 18 '22 18:10

Dave Griffith