0

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?

bsky
  • 19,326
  • 49
  • 155
  • 270
  • 1
    You cannot access `this.url` from the object, because the **object** does not have a field named `url`. If you're trying to access the `url` from an instance of the class, then how is the object supposed to know from which instance of the class you want to access `url`? This is the equivalent of the Java question where you cannot access instance members from a static method. It looks like you have a misunderstanding about Scala classes and objects. – Jesper Mar 07 '16 at 13:55

2 Answers2

4

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
  }
}
Wellingr
  • 1,181
  • 1
  • 9
  • 19
2

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.

Community
  • 1
  • 1
John K
  • 1,285
  • 6
  • 18