Graph View Android Library

GraphView graph = (GraphView) findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<>(new DataPoint[] {
          new DataPoint(0, 1),
          new DataPoint(1, 5),
          new DataPoint(2, 3)
});
graph.addSeries(series);

I have this Java Code from the Graph View Library. I am unable to convert this into Kotlin code for the Android Application that I am building in Kotlin. How shall I be doing this?

Help is required!!

If you want a 1:1 conversion to Kotlin it will look more less like this:

val graph = findViewById(R.id.graph) as GraphView
val series = LineGraphSeries(arrayOf(DataPoint(0, 1), DataPoint(1, 5), DataPoint(2, 3)));
graph.addSeries(series)
1 Like

I think we don’t need new keyword here and also the semicolon at the end.

Sorry, I was writing this code by hand and didn’t remember to erase that part :slight_smile:

How else can you write the code? How can I message you privately here? I am new to the site.

To send a private message you can just enter the user’s profile and click the “Message” button.

But I will tell you beforehand @thebali that I’m not an Android developer, so I can help you only with language itself, but not with the platform or libraries :wink:

Here arrayOf(DataPoint(0,1))

different from mutableListOf(DataPoint(0,1)). But, I don’t understand how?

Array is invariant on T (Array is not Array), the same for MutableList, but List is covariant (List is List).
Found this from SO.

And what does invariant on T means .?

If type T is invariant, that means that a class with declated type T has methods consuming and producing objects of type T. In case of MutableLists and Arrays you can put objects and fetch them.

val mutableList: MutableList<T> = mutableListOf(t1, t2)
mutableList[0] = t3
val element: T = mutableList.first()

but you can’t assign invariant types like this:

val intList: MutableList<Int> = mutableListOf(1, 2, 3, 4)
val numberList: MutableList<Number> = intList // compilation error

to make it work, you have to project generic type as covariant:

val intList: MutableList<Int> = mutableListOf(1, 2, 3, 4)
val numberList: MutableList<out Number> = intList
val number: Number = numberList.first()
numberList[0] = 1 // compilation error, because covariant types work only with methods returning generic type

List (or read-only list) has only methods producing type T so its’ generic type has been declared as covariant by default. So declaration like this one is allowed:

val intList: List<Int> = mutableListOf(1, 2, 3, 4)
val numberList: List<Number> = intList
val number: Number = numberList.first()
numberList[0] = 1 // compilation error, there is no such method in List<T>

Contravariant types are the exact oposite of it, because you can operate only on methods where T is used as method arguments.

I hope that I made it clear to you :slight_smile: