user972946
user972946

Reputation:

What is "(), the Unit value"?

My scalatest unit test fails with the following message:

<(), the Unit value> was not equal to object ...

What is the type and value of "the Unit value"?

Upvotes: 4

Views: 4625

Answers (2)

Cygil
Cygil

Reputation: 391

http://www.scala-lang.org/api/current/scala/Unit.html

"Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void."

The unit value is returned from any expression that doesn't have any other return type, eg

> val q = 1 until 10 foreach (_+1) // arbitrary expression of type Unit is assigned to q
q: Unit = ()

When you define a function like this:

def foo(x: Int) { 
 ..
}

Scala expects Unit to be returned. It's equivalent to

def foo(x: Int): Unit = { .. }

In short: Unit is like void in Java or C++, except in Scala no expression literally "returns nothing." If an expression/function is of type Unit it represents something that returns nothing of any real interest. I assume somewhere in your unit test you have something that returns () when you were expecting it to return something of a different value; possibly you have written

def foo {
 ..
  val result = something
}

Instead of

def foo: SomethingType = {
  ..
  val result = something
  result
}

Upvotes: 5

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

The type is Unit and the only value this type can take is the literal ().

Upvotes: 15

Related Questions