Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Unit.type and Unit

Tags:

types

scala

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?

like image 417
CalumMcCall Avatar asked Jan 30 '23 01:01

CalumMcCall


2 Answers

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(_ => ())
like image 183
Levi Ramsey Avatar answered Feb 03 '23 12:02

Levi Ramsey


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.

like image 28
Alexey Romanov Avatar answered Feb 03 '23 14:02

Alexey Romanov