CalumMcCall
CalumMcCall

Reputation: 1687

What is the difference between Unit.type and Unit

I have the method below:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] = {
  val f = Future.sequence(notifications.map(insert)).map(_ => Unit)
  f.onFailure { case ex => sys.error(s"Got exception whilst saving PushNotification: $ex") }
  f
}

It gives the following compiler error:

  type mismatch;
  found   : scala.concurrent.Future[Unit.type]
  required: scala.concurrent.Future[Unit]
     f
     ^

I thought Unit was a type with a single element, thus there shouldn't be any confusion when it comes to Unit. I tried googling this but I couldn't find any more information about what "Unit.type" is.

If I simplify the method like this, then it works fine:

override def insertAll(notifications: Seq[PushNotificationEncoded])
                      (implicit ec: ExecutionContext): Future[Unit] =
  Future.sequence(notifications.map(insert)).map(_ => Unit)

What is going on here?

Upvotes: 4

Views: 868

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170713

x.type is the singleton type of x: the type whose only two values are x and null. x must be a "stable identifier" of a value, such as the companion object of Unit.

Upvotes: 2

Dima
Dima

Reputation: 40500

Types in scala are objects too, and, as any object, have their own types. () is an instance of type Unit. Unit is an instance of Unit.type. (I don't think there is a way to go even higher - no such thing as Unit.type.type though).

For most non-esoteric purposes, you don't need to worry about it, just use () whenever you need to reference an instance of type Unit, you shouldn't really need the other one anywhere.

Upvotes: -1

Levi Ramsey
Levi Ramsey

Reputation: 20551

Unit's sole instance is (). Unit used as a value is the companion object for Unit (which mainly manages boxing and unboxing)

val f = Future.sequence(notifications.map(insert)).map(_ => ())

Upvotes: 7

Related Questions