kornfridge
kornfridge

Reputation: 5200

How to get fields with same name as class parameters in Scala?

Take a simple class like the following:

class Person(name: String, age: Int) {}

Now, when I instantiate this class, I typically want its users to be able to use name and age. Like:

val ronald = new Person("Ronald", 22)
val ronaldsName = ronald.name  // <-

This doesn't work of course unless I either define a getter called name, or make Person a case class. The latter is an easy solution, but I sort of feel like I'm abusing case classes?

Still the former is kind of a little inconvenient since I can't simply:

class Person(name: String, age: Int) {
  def name = name
}

So, then I would have to rename the first name in the class's constructor to something else, like personName or _name or n. But that is sort-of confusing and far less elegant in my eyes. It's the same concept/variable/value, so it should have the exact same name, right?

So ... what is the best or correct practice here? It's so tempting to just add that case.

Upvotes: 2

Views: 1650

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 59994

You just need to add val to turn your parameters into public fields of your class:

class Person(val name: String, val age: Int)
             ^^^               ^^^

Case classes, as you noticed, do this by default.

Upvotes: 9

Related Questions