Skip to content
Advertisement

Java to Kotlin conversion

Here is a Piece of code in java.

Private ImageView[] = dots;
dots = new ImageView[int]; // Int Will be the size of ImageView

How can i convert this in kotlin.

I Tried,

lateinit var dots: ArrayList<ImageView>

But this does not give me the size.

Advertisement

Answer

You can initialize list like this:

val initialSize = 5
var dots = ArrayList<ImageView>(initialSize)

dots is a Mutable, No Fixed Size list of elements.

You can change elements at specific indexes and add new elements, e.g.:

dots[1] = ImageView()
dots.add(ImageView())

Also there are other ways to create arrays and lists in Kotlin:

// Arrays
var myArray = Array<Int>(5) { 0 }   // Mutable, Fixed Size, all elements initialized with 0
var myArray1 = arrayOf(10, 20, 30)  // Mutable, Fixed Size
var myArray2 = arrayOfNulls<Int>(5) // Mutable, Fixed Size, all elements initialized with null
var myArray3 = emptyArray<String>() // Mutable, Fixed Size

// Lists
val immutableList: List<Int> = listOf(1, 2, 3, 4, 5, 2) // Immutable, Fixed Size
val mutableList1 = arrayListOf<String>() // Mutable, No Fixed Size
var mutableList2 = ArrayList<Double>()   // Mutable, No Fixed Size
var mutableList22 = ArrayList<Double>(10) // Mutable, No Fixed Size
var mutableList3 = arrayListOf(*myArray1) // Mutable, No Fixed Size
val mutableList: MutableList<Int> = mutableListOf(5, 4, 3, 2, 1) // Mutable, No Fixed Size
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement