48

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 Answers1

101

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) ...
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 4
    It may be worth noting that (IIRC) this creates a new array. – Salem Nov 26 '17 at 19:08
  • 2
    I believe https://youtrack.jetbrains.com/issue/KT-20462 fixes this performance/memory allocation issue. 1.2-Beta2 contains this fix. – Mikezx6r Nov 28 '17 at 12:33
  • This works. I now wonder how you would do this on Java. Does anyone know? – android developer Oct 15 '18 at 09:46
  • @androiddeveloper - I don't think you need to do anything special in Java. This just works: `void a(String... strings) { /* Stuff */ } void b(String... strings) { a(strings); }`. – Oliver Charlesworth Oct 15 '18 at 12:26
  • @OliverCharlesworth OK thanks. I was sure it didn't work for me at some point, as this is actually what I've tried, but now on POC it does work, so something else must have caused the initial error. – android developer Oct 15 '18 at 13:10