问题
I want to create POJO class in Scala with only default empty constructor. In java, it's like this:
public class Foo {
private String name;
private String address;
...
//and the public getter/setter below...
}
In scala, I have seen that you can create POJO like this:
case class Foo(var name: String, var address: String, ...)
But in my case, the class will have many properties (around 50+), and I don't think instantiating the class with 50 constructor parameters is fit for this case.
UPDATE:
Also, the class's properties value can be set (it's not read-only). This is how I expect the usasge of the POJO class:
val foo = new Foo()
foo.name = "scala johnson"
foo.address = "in my sweeet dream, oh yeah"
...
回答1:
How about :
class C {
var p1:String = _
var p2:Int = _
}
回答2:
If you don't need to instantiate the class with parametrized constructor, and you are going to have many properties, then perhaps you need either an object (a collection of static properties and methods) or a non-case class.
Example of an object:
object Foo {
val someString = "one"
val someNumber = 42.5
}
There can be also a non-case class. You can have a class without arguments though I am not sure why would you want to have a class in that case:
class Foo {
val someString = "one"
val someNumber = 42.5
}
You call them like that:
val myObjectString = Foo.someString
val myClass = new Foo
val myClassNumber = myClass.someNumber
来源:https://stackoverflow.com/questions/27787505/how-to-create-pojo-class-with-only-empty-constructor-in-scala