Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass vararg to a varag function or constructor in Kotlin?

Tags:

kotlin

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?

like image 984
Rafael Ferreira Rocha Avatar asked Nov 26 '17 18:11

Rafael Ferreira Rocha


People also ask

How do you pass Varargs parameter in Kotlin?

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.

What is keyword Vararg in Kotlin used for?

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 .


1 Answers

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) ... 
like image 82
Oliver Charlesworth Avatar answered Sep 20 '22 09:09

Oliver Charlesworth