Teimuraz
Teimuraz

Reputation: 9335

Scala: Type declaration on Literal

In slick "dynamic filter" example I've encountered the syntax which haven't seen before in Scala:

true: Rep[Boolean]

val q4 = coffees.filter { coffee =>
  List(
      criteriaColombian.map(coffee.name === _),
      criteriaEspresso.map(coffee.name === _),
      criteriaRoast.map(coffee.name === _) // not a condition as `criteriaRoast` evaluates to `None`
  ).collect({case Some(criteria)  => criteria}).reduceLeftOption(_ || _).getOrElse(true: Rep[Boolean])
}

So I've tried in repl something like: 1: Int, "s": String

What is it used for? To explicitly specify the type of literal?

Upvotes: 1

Views: 61

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44957

This here:

(expression : Type)

is called a type ascription. It is used to either ensure that your assumptions about the type of certain expressions in your code is correct, or to help the compiler with the type inference.

There is a third use of that: to enforce implicit conversion to the specified type.

I'm not a specialist when it comes to coffee, but the only plausible explanation for it is:

  • There is a type constructor Rep[X] somewhere in scope
  • In the implicit scope, there is an implicit conversion with signature

-

implicit def booleanIsRep(b: Boolean): Rep[Boolean] = ...

or, alternatively:

  • In the implicit scope there is a polymorphic conversion with signature

-

implicit def everythingCanWrapToRep[X](x: X): Rep[X] = ...

You might try to add compiler option -print to see where implicit conversions are inserted.

Upvotes: 2

Related Questions