Showing posts with label Tuple. Show all posts
Showing posts with label Tuple. Show all posts

Monday, October 9, 2017

Type conversion to Unit in Scala

In Scala we can write the following which raises the concern how the type conversion works for Unit type.

def f(a: Unit) = println("invoked f with Unit type: " + a)

f(42)
f("temp")

The type conversion is not based on any implicit conversions defined in Predef object or is not based on sub-typing.

As per Scala Language Specification (SLS) there is an implicit conversion performed by the compiler. Excerpt form the SLS below -

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

The only value that Unit type can take is (). It does not represent any runtime object and is defined in the SLS section 12.2.3.

Moreover, a 0-tuple is also represented using the Unit value [SLS section 6.9]. It denotes the absence of any useful value, which makes sense since for a 0-tuple, there is no operation that seems to be useful. However, this results another type for tuples to deal with as if Tuple1, Tuple2, Tuple3.... Tuple22 wasn't enough.

PS: To generate a warning for this implicit conversion we can use scalacOptions += "-Ywarn-value-discard" in SBT configuration