Automatically make getters for class parameters (to avoid case classes)?

In Scala, if we have

class Foo(bar:String)

We can create a new object but cannot access bar

val foo = new Foo("Hello")
foo.bar // gives error

However, if we declare Foo to be a case class this works:

case class Foo(bar:String) 
val foo = Foo("hello")
foo.bar // works

I am forced to make many of my classes as case classes because of this. Otherwise, I have to write boilerplate code for accessing bar:

class Foo(bar:String) {
  val getbar = bar
}

So my questions are:

  1. Is there any way to "fix" this without using case classes or boilerplate code?
  2. Is using case classes in this context a good idea? (or what are the disadvantages of case classes?)

I guess the second one deserves a separate question.

Answers


Just use val keyword in constructor to make it publicly accessible:

class Foo(val bar:String) {

}

As for your question: if this is the only feature you need, don't use case classes, just write with val.

However, would be great to know why case classes are not good.

In case classes all arguments by default are public, whereas in plain class they're all private. But you may tune this behaviour:

scala> class Foo(val bar:String, baz: String)
defined class Foo

scala> new Foo("public","private")
res0: Foo = Foo@31d5e2

scala> res0.bar
res1: String = public

scala> res0.baz
<console>:10: error: value baz is not a member of Foo
              res0.baz

And even like that:

class Foo(private[mypackage] val bar:String) {
  // will be visible only to things in `mypackage`
}

For case classes (thanks to @JamesIry):

case class Bar(`public`: String, private val `private`: String)  

Need Your Help

Ant to Maven - multiple build targets

ant build maven target

I have an Ant build that is currently being converted to Maven. However, the Ant build has 2 build targets - one that builds the entire app, and one that builds a JAR from some of those files (only a

What utilities can provide database hits/duration per page?

asp.net sql-server profiler

SQL Server profiler is great for profiling SQL Server performance for web apps. However, when I'm testing my webapp I'd like a summary of database hits/duration per page.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.