score:1

Accepted answer

let's first take reflection out of the picture completely, and just try to do what you are doing without using reflection:

class b(p1: int = 0, p2: string = "")

class a extends b

//val b = (new a(1, "c")).asinstanceof[b]

// even simpler:
val b = new a(1, "c")
// error: too many arguments for constructor a: ()a
//        new a(1, "c")
//        ^

as you can see, it doesn't even compile. why? well, you defined a's constructor to take no arguments! somehow, during the reflection process, this information gets lost and you end with a legal call passing arguments to a constructor that doesn't take any and just ignores them.

score:1

i don't know the underlying reason, but it probably has to do with some quirk in how reflection works at runtime.

in any case this kind of code will get you what you want (without repeating the default values specified in the superclass). note that you should explicitly specify the parameters from the superclass you are using in the subclass:

class b (p1: int = 0, p2: string = "") {
  override def tostring: string = s"p1 = $p1, p2 = $p2"
}

class a (p1: int, p2: string) extends b (p1, p2) { }

...

val obj: b = constructor(1, "c").asinstanceof[b]
println(obj)

output:

p1 = 1, p2 = c

Related Query

More Query from same tag