alex.melnyk
alex.melnyk

Reputation: 15

Scala method call parameters with colon

final def apply(block: => Result): Action[AnyContent] =
    apply(BodyParsers.utils.ignore(AnyContentAsEmpty: AnyContent))(_ => block)

Does Anybody know what does this AnyContentAsEmpty: AnyContent mean ? Particularly : AnyContent ?

Upvotes: 1

Views: 905

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369498

Does Anybody know what does this AnyContentAsEmpty: AnyContent mean ?

It is a Typed Expression.

Particularly : AnyContent ?

This is a Type Ascription, which is used to ascribe a type to an expression, thus making the expression a typed expression.

Normally, Scala computes the types of expressions without your help, but you can ascribe a specific type to an expression, if you don't like the one that Scala computes.

For example, for the expression

42

Scala computes the type Int. You could also write

42: Int

instead, and you would get the same result. If you don't want 42 to be typed as Int, you can ascribe a different type to it, e.g.:

42: Long

Now, the expression has type Long instead of Int. If you were to assign it to a val, for example, and don't provide a type for the val, Scala would infer type Long:

val a       = 1       // 1 has type Int, therefore Scala infers type Int for a
val b: Long = 1       // b is typed as Long, therefore Scala converts 1 to a Long
val c       = 1: Long // 1 is typed as Long, therefore Scala infers type Long for c

You can use this to guide Scala to infer a more sensible type, or to pick a particular overload.

Upvotes: 4

HTNW
HTNW

Reputation: 29193

An expression of the form expr: Type simply means the value of expr, but with the type Type. This is useful in guiding type inference. That is, the expression

AnyContentAsEmpty

has type

AnyContentAsEmpty.type

while

AnyContentAsEmpty: AnyContent

has type

AnyContent

I'm not sure why it's being used here, but maybe you can remove the : AnyContent and see what happens.

This syntax, called a type ascription, has two other uses: Implicit conversions and varargs. Also, note how it's similar to a variable declaration/case statement (val x: Any = ???/case x: String => ???).

class Base
class Extn
implicit def Base2Extn(b: Base) = new Extn
val x = new Base // x has type Base
val y = new Base: Extn // y is Base2Extn(new Base), with type Extn

def f(args: Any*): Unit = args match {
  // `tail: _*` is like saying "use tail as a bunch of arguments instead of just one"
  // Bit of a stretch but I think that's why the syntax was chosen
  case head +: tail => { println(head); f(tail: _*) }
  case _ => ()
}

Upvotes: 1

Related Questions