简体   繁体   English

如何在Scala中仅使用空构造函数创建POJO类?

[英]How to create POJO class with only empty constructor in Scala?

I want to create POJO class in Scala with only default empty constructor. 我想在Scala中使用仅默认的空构造函数创建POJO类。 In java, it's like this: 在Java中,就像这样:

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: 在scala中,我看到您可以像这样创建POJO:

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. 但是在我的情况下,该类将具有许多属性(大约50个以上),并且我认为用50个构造函数参数实例化该类不适合这种情况。

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: 这就是我期望使用POJO类的方式:

val foo = new Foo()
foo.name = "scala johnson"
foo.address = "in my sweeet dream, oh yeah"
...

How about : 怎么样 :

class C {
  var p1:String = _
  var p2:Int = _
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM