Search code examples
kotlininitializationoptional-parametersoptional-arguments

Kotlin and constructors, initializing


Sorry for asking a very newbie Kotlin question, but I'm struggling to understand some of the things related to constructors and intitializing.

I have this class and constructor:

class TestCaseBuilder constructor(
     caseTag: String = "Case",
     applType: Buy.ApplFor = Buy.ApplFor.PROOFFINANCE,
     komnr: String = "5035") {

     var caseTag: String       = caseTag
     var applType: Buy.ApplFor = applType  
     var komnr: String         = komnr             

What I'm trying to do here is to have three optional parameters in the constructors, using default values for them. The reason I'm declaring them in the class body is because I need to have access to them from the main class.

Now, this code works. No errors when I run it. But IntelliJ gives the following comment for the variables (ex.: caseTag):

Property is explicitly assigned to parameter caseTag, can be declared
directly in constructor.

What I've found when searching this is examples using an init {}, but the result I've gotten to includes initializing the variables twice, once in the constructor and then in the init {}. Which clearly isn't correct, I'd say?

What's a better what to have (or than having) optional parameters in the constructor, and then creating class variables from them?


Solution

  • You can declare properties directly in primary constructor. That means you can drop explicit declarations in class body:

    class TestCaseBuilder constructor(
         var caseTag: String = "Case",
         var applType: Buy.ApplFor = Buy.ApplFor.PROOFFINANCE,
         var komnr: String = "5035")
    

    You can also drop the constructor keyword if your primary constructor does not have any annotations or visibility modifiers (defaults to public).