Search code examples
scalascala-2.11

what is the use of [] these brackets in case class before parameter list in scala


Maybe my questions seems not valid but I am unable to understand the concept in the code. Here is the code

case class Response[Body](request: Request, status: Int, headers: Map[String, Seq[String]], body: Body)

case class Request(method: String,
                     url: String,
                     state: JsValue = JsNull,
                     headers: Map[String, String] = Map.empty,
                     body: ReqBody = EmptyReqBody) extends Scraped

In this piece of code i am confused on this part

case class Response[Body] 

I have never used [] these brackets before passing parameter list in scala so i am unable to get thing. I am also confused on this line too

, body: Body)

What is Body? Why is it there in these Square brackets Please help me and am sorry if i am asking something which is not making sense.


Solution

  • These declarations are equal:

    case class Response[Body](request: Request, ... , body: Body)
    case class Response[T](request: Request, ... , body: T)
    case class Response[YourPreferredName](request: Request, ... , body: YourPreferredName)
    

    Usage:

    val responseWithStringBody:Response[String] = Response(..., "hello")
    val responseWithIntBody:Response[Int] = Response(..., 1024)
    ...
    val responseWithUserBody:Response[User] = Response(..., User("name"))
    

    In this case you use invariant type parameter - Body. There are also contravariant, covariant type parameters:

    case class Response[Body]   // invariant (your case)
    case class Response[+Body]  // covariant
    case class Response[-Body]  // contravariant