Dragonborn
Dragonborn

Reputation: 1815

What is difference between Unit and ()?

I thought () was the only instance of Unit in Scala.

When I try to set a function to anonymous func variable, this works:

def some(a:Unit):Unit = {
    println("Enigma")
}
val func:Unit => Unit = some
func()

But this does not:

def some():Unit = {
    println("Enigma")
}
val func:Unit => Unit = some

Upvotes: 4

Views: 1207

Answers (3)

xnnyygn
xnnyygn

Reputation: 741

def some(): Unit

The () here is not the instance of Unit, just no argument.

The normal usage of () is

def some(): Unit = ()

But if you enter Some() in Scala interpreter, you will get

scala> Some()
res0: Some[Unit] = Some(())

Well, it's strange, seems that Scala rewrites Some() to Some(()). Anyway, I will not write code like this, it makes things hard to understand.

Upvotes: 1

Justin Pihony
Justin Pihony

Reputation: 67135

This is because your second example is a method without any arguments.

Take a look at the types that results:

some: (a: Unit)Unit
some: ()Unit

which would be written in a type assignment as

Unit => Unit
() => Unit

In the second case, the parens are not acting as Unit, but instead are merely the string representation of an argumentless function. () is only symbolic as Unit in the context of a method. In a type signature you use Unit, because () is expected to be a function with no arguments

Upvotes: 1

Rich Henry
Rich Henry

Reputation: 1849

An empty parameter list as in your second example is not the same as Unit which is a value that represents something like null. () doesn't always mean Unit in every context, specifically the instance where your dealing with an argument list.

Upvotes: 3

Related Questions