How to Pass vararg to a varag function or construc

2019-04-09 02:23发布

问题:

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?

回答1:

From the docs:

Inside a function a vararg-parameter of type T is visible as an array of T.

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


标签: kotlin