How can I create an instance of a Case Class with constructor arguments with no Parameters in Scala?

后端 未结 4 1865
清歌不尽
清歌不尽 2020-12-10 17:23

I\'m making a Scala app that sets by reflection field values. This works OK.

However, in order to set field values I need a created instance. If I have a class with

4条回答
  •  心在旅途
    2020-12-10 17:37

    If you are looking for a way to instantiate the object with no arguments, you could do the same as you did in your example, just so long as your reflection setter can handle setting the immutable vals.

    You would provide an alternate constructor, as below:

    case class Person(name : String, age : Int) {
        def this() = this("", 0)
    }
    

    Note that the case class will not generate a zero-arg companion object, so you will need to instantiate it as: new Person() or classOf[Person].newInstance(). However, that should be what you are looking to do.

    Should give you output like:

    scala> case class Person(name : String, age : Int) {
         |         def this() = this("", 0)
         |     }
    defined class Person
    
    scala> classOf[Person].newInstance()
    res3: Person = Person(,0)
    

提交回复
热议问题