-3

I made this code for to drawing polygon in googlemaps android. I made from this lib Map Drawing.

I made this code with kotlin, i get error. Here is my code:

...
    private fun getMarkers(points: Array<LatLng>): List<ExtraMarker> {
        val extraMarkers: List<ExtraMarker> = ArrayList()
        @IdRes val icon = R.drawable.ic_add_polypoint
        for (latLng in points)
        {
            val extraMarker = ExtraMarkerBuilder()
                    .setCenter(latLng)
                    .setIcon(icon)
                    .build()
            extraMarkers.add(extraMarker) <--- error in here (add)
        }
        return extraMarkers
    }

Error in here

extraMarkers.add(extraMarker)

I build from this code:

private List<ExtraMarker> getMarkers(LatLng[] points) {
        List<ExtraMarker> extraMarkers = new ArrayList<>();
        @IdRes int icon = R.drawable.ic_beenhere_blue_grey_500_24dp;
        for (LatLng latLng : points) {
            ExtraMarker extraMarker =
                    new ExtraMarkerBuilder()
                            .setCenter(latLng)
                            .setIcon(icon)
                            .build();
            extraMarkers.add(extraMarker);
        }
        return extraMarkers;
    }

Please help me, how can fix it? Thank you.

Community
  • 1
  • 1
Bara19
  • 1
  • 1
  • 7

2 Answers2

0

Try this.

private fun getMarkers(points: Array<LatLng>): List<ExtraMarker> {
        val extraMarkers: ArrayList<ExtraMarker> = ArrayList()
        @IdRes val icon = R.drawable.ic_add_polypoint
        for (latLng in points)
        {
            val extraMarker = ExtraMarkerBuilder()
                    .setCenter(latLng)
                    .setIcon(icon)
                    .build()
            extraMarkers.add(extraMarker) 
        }
        return extraMarkers
    }

Hope this will help.

Some explanation

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

Zeeshan Shabbir
  • 6,704
  • 4
  • 38
  • 74
0

For those who just begin the tour of Kotlin, especially come from Java, I suggest you try this site: http://try.kotlinlang.org/

There is a button call convert from Java:

enter image description here

By using this method, you can copy the original Java snippet and easily convert to Kotlin code. For example, I take your original Java code and paste to the dialog then I got this result:

enter image description here

Easy to use, and it's helpful if you are just start to code in Kotlin.

Anthonyeef
  • 2,595
  • 1
  • 27
  • 25