bsky
bsky

Reputation: 20222

Connecting case class with object in model

I have started learning about Play, and in the tutorials that I saw, the model usually has two components: a case class and an object.

I have created a model with an object and a case class. My question is how do I reference a field(declared in the case class) from the object:

package models

import java.net.URL
import play.api.Logger
import play.api.db.DB
import play.api.libs.json.Json

case class Page(url: String)

object Page {
  implicit val personFormat = Json.format[Page]

  def readPageContent(): String = {
    var content: String = new URL(this.url).getContent().toString
    return content
  }
}

For instance, here in the object, I am trying to reference the field url using this.url, but I get cannot resolve symbol url.

How can I reference the field?

Upvotes: 0

Views: 112

Answers (2)

Wellingr
Wellingr

Reputation: 1191

In order to reference a field of a case class instance you need a reference to the instance itself. Looking at your code, you can achieve this in two ways:

Adding a parameter to the readPageContent method:

def readPageContent(page: Page): String = {
  new URL(page.url).getContent().toString
}

Moving the readPageContent method to the Page class itself:

case class Page(url: String) {
  def readPageContent(page: Page): String = {
    new URL(this.url).getContent().toString
  }
}

Upvotes: 4

John K
John K

Reputation: 1285

You can't. Any field from object can be accessed from the corresponding class definition, but not the opposite. In an oversimplified way, you can think of the object as the static part of the class (where in java you would have used static). For more details, you can look at this SO question.

Upvotes: 2

Related Questions