Default values through inheritance

Hey there, default values are easy to use with functions,… I tried using them with Classes instead through inheritance and its not working… Is it a feature that only works for functions?


open class Shape(open val name:String)
open fun area() = 0.0

class Circle(override val name : String = "Big circle" , val radius : Double) : Shape(name) 
override fun area(): Double  = Math.PI * Math.pow(radius, 2.0)
fun main(args: Array<String>) {
// Use inheritance...
val smallCircle = Circle(7.0)  // TRIED TO USE DEFALUT VALUE HERE...

// properties from object

// get area
println("The area is: ${smallCircle.area()}")

Is there a specific reason this feature does not work with classes?

Default parameters must be last in the function (or constructor) invocation. If you swap the order of name and radius in the Circle constructor it should all work.


That worked : yes, true true, so many rules to look into but al get it… Thanks alot @al3c :face_with_hand_over_mouth: :innocent: :face_with_hand_over_mouth: :innocent:

1 Like

al3c is correct, I would like to add a sugar to the story.

If, for some reason, the swapping of arguments is not an option (for example, this is a API already used), you can use named arguments for calling:

val smallCircle = Circle(radius = 7.0)  

It’s my preference, but I often use named arguments in function calls even when it is not strictly required, when.

  • There are more than 4-5 arguments:
  • There are arguments of the same type
  • When I pass constant values instead of variables (I know IDEA helps here.)

These make reading the code much easier.