Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the following scala code is valid?

Tags:

scala

My understanding is Unit = void, but why I can pass in multiple argument?

So can anyone explain why the following code is valid?

def foo(x: Unit) = println("foo")                 
foo("ss", 1)  
like image 463
Howard Avatar asked Oct 12 '12 10:10

Howard


People also ask

What is Scala code used for?

Scala is used in Data processing, distributed computing, and web development. It powers the data engineering infrastructure of many companies.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

How is Scala code executed?

Executing Scala code as a script Another way to execute Scala code is to type it into a text file and save it with a name ending with “. scala”. We can then execute that code by typing “scala filename”. For instance, we can create a file named hello.

Why should I use Scala?

The Advantages of ScalaScala has an exact syntax, eliminating boilerplate code. Programs written in Scala require less code than similar programs written in Java. It is both an object-oriented language and a functional language. This combination makes Scala the right choice for web development.


2 Answers

If you run your snippet with scala -print you'll roughly get the following output for the code:

/* Definition of foo */
private def foo(x: scala.runtime.BoxedUnit): Unit = {

/* Invocation of foo */
foo({
  new Tuple2("ss", scala.Int.box(1));
  scala.runtime.BoxedUnit.UNIT
});

As you can see, the arguments to foo are rewritten into a code block that creates a tuple but then returns UNIT.

I can't see a good reason for this behaviour and I'd rather get a compiler error thrown instead.

like image 184
Malte Schwerhoff Avatar answered Nov 03 '22 01:11

Malte Schwerhoff


A related question which gives a decent answer to this is here:

Scala: Why can I convert Int to Unit?

From Section 6.26.1 of the Scala Language Specification v2.9, "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; () }.

So, in your case it seems ("ss", 1) is being converted to a tuple so that it can be treated as a single argument, then as that argument type is not Unit, it is converted to a block which computes that tuple value then returns unit to match with the required type of the parameter.

like image 37
iainmcgin Avatar answered Nov 03 '22 02:11

iainmcgin