简体   繁体   中英

What does () mean in Scala?

I've found a Scala code snippet which declares a method <init> and puts () right below the invocation.

I have a question about line number 5. What does () mean here?

(() => {
  final class $anon extends MutableProjection {
    def <init>() = {
      super.<init>();
      ()
    };
    ...
  };
  new $anon()
})

Here is a code with full example.

Every Scala function has a return type. By convention (and highly encouraged by some language features), functions that don't need to return anything have a return type called Unit , which has a singleton value written as () .

The last expression in a function body is its return value. That author made this be () to cause the compiler to infer that the return type should be Unit . But it would have been more clear to just do that with a type annotation. If a function's return type is Unit , Scala will implicitly return () from the function no matter what the last statement in the body is. So this

def <init>() = {
  super.<init>()
  ()
}

could be written equivalently as

def <init>(): Unit = super.<init>()

() can meean a few things, depending on context.

As a value, it is an empty tuple, or the singleton type. It's type is Unit .

It can denote a function or method that takes no parameters, such as:

def foo() = "Hello world"

Note that when writing an anonymous function, the () is by itself but still means a function with no parameters.

val x = () => 2

The type of x is () => Int , a function taking no parameters and returning an int.

As a source of infinite confusion, you can get examples like this:

val y = () => ()

The type of y here is () => Unit , a function of no parameters returning Unit , not Unit => Unit , which would be writen as val z = (x:Unit) => () , and called like z(())

The unit vs empty parameter distinction has been awkward for me in the past so hopefully that demystifies some of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM