Default arguments not carrying in to object creation

I have my primary constructor created as follows, matching Listing 13.7

class Player(_name: String,
         var healthPoints: Int = 100,
         val isBlessed: Boolean,
         private val isImmortal: Boolean) {

I then try to create objects of type Player

val hero = Player("Madrigal", 100, false, false)
val npc = Player("Madrigal", true, false)

The hero object is created fine. IntelliJ gives an error for the npc object stating

None of the following functions can be called with the arguments supplied.
<init>(String) defined in Player
<init>(String, Int = ..., Boolean, Boolean) defined in Player

If I use named arguments then the default argument is applied for healthPoints

val npc = Player(name="Madrigal", isBlessed=true, isImmortal=false)

and no error is displayed. Is there a proper way to use the constructor variants?

1 Like

If you use

val npc = Player("Madrigal", true, false)

The Compiler will look for

Player(_name="Madrigal", healthPoints=true, sBlessed=true, isImmortal=?)   //Wrong

Remember these tips:

  1. Use all “position argument” before “named argument”.
  2. If you start using “default value”, all argument after this should use “named argument”
val npc = Player(name="Madrigal", isBlessed=true, isImmortal=false)   //Right and Only choice to use default value