Variable Number of Arguments in Methods in Kotlin

Often times, there are situation where we don’t know much parameters or arguments would be passed in method.



This is done in Java using three dots like this:

void anySampleMethod(Int... intList)        // Note the three dots after the type
{
    // Now you can access these in for loop.
    for (Int myInt : intList)
    {
        // Do anything with myInt here
        myInt += 10;
    }
}

// When calling this method
anySampleMethod(1,2,3,4);       // Passed 4 arguments
anySampleMethod(2);             // Passed 1 argument

To do this in Kotlin, we will use vararg which means variable arguments.

fun anySampleMethod(varargs intList: Int)       // Note the vararg before the variable name and the type
{
    // Now you can access these arguments in loop
    for (myInt in intList)
    {
        // Do anything with myInt here
        myInt += 10
    }
}


// When calling this method
anySampleMethod(1,2,3,4);       // Passed 4 arguments
anySampleMethod(2);             // Passed 1 argument


If you liked this article, you can read my new articles below:


Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan