Kotlin does not allow my subclass to pass vararg to my super class constuctor Here is my Operation class:
package br.com.xp.operation import java.util.ArrayList abstract class Operation(vararg values: Value) : Value { protected var values: MutableList<Value> = ArrayList() internal abstract val operator: String }
and here is my SubtractionOperation class:
package br.com.xp.operation class SubtractionOperation private constructor(vararg values: Value) : Operation(values) { override val operator: String get() = "-" }
The compile says:
Type mismatch Required Value found Array
Can anyone explain why this is not possible?
In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.
Kotlin Android. Sometimes we need a function where we can pass n number of parameters, and the value of n can be decided at runtime. Kotlin provides us to achieve the same by defining a parameter of a function as vararg .
From the docs:
Inside a function a
vararg
-parameter of typeT
is visible as an array ofT
.
So in the SubtractionOperation
constructor, values
is really an Array<Value>
. You need to use the spread operator (*
) to forward these on:
class SubtractionOperation private constructor(vararg values: Value) : Operation(*values) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With