user9347168
user9347168

Reputation:

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?

Upvotes: 1

Views: 3618

Answers (2)

Jeffery Ma
Jeffery Ma

Reputation: 3351

@JvmOverloads annotation can over load the constructor with different param size

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

Then the class got three constructor with optional param

val a = TestCaseBuilder("CaseA")
val b = TestCaseBuilder("CaseB", Buy.ApplFor.SomethingElse)
val c = TestCaseBuilder("CaseB", Buy.ApplFor.SomethingElse, "1111")

Upvotes: -1

Pawel
Pawel

Reputation: 17288

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).

Upvotes: 7

Related Questions