-1

I am working on a simple app (To-Do List app). I created a class called tasks:

class tasks(var title:String, var time:String)

and stored some tasks in an ArrayList:

fun main(args: Array<String>){
    var tasks_list = ArrayList<tasks>(tasks("hello","3am"),tasks("meet amy","5pm"))
}

But still it gives me an error: the error

Can you please explain why it doesn't work? And how to print out a task. Thanks.

aaron
  • 39,695
  • 6
  • 46
  • 102
Funris
  • 51
  • 1
  • 10

1 Answers1

1

It seems you are not initializing the ArrayList correctly.

You might do something like:

fun main(args: Array<String>) {
    var tasks_list = arrayListOf<tasks>(tasks("hello","3am"), tasks("meet amy","5pm"))
    println(tasks_list)
}

Instead. Alternatively, this would also work:

var tasks_list = arrayListOf<tasks>()
tasks_list.add(tasks("hello","3am"))
tasks_list.add(tasks("meet amy","5pm"))
println("Tasks list:")
println(tasks_list)

However, without overriding toString() this would only print some kind of object reference that looks like the following:

Tasks list:
[tasks@28a418fc, tasks@5305068a]

In your tasks class, you should override toString() so that it prints something useful, like follows:

class tasks(var title:String, var time:String) {

    override fun toString() : String = "{Title: $title. Time: $time}"

}

Now your output will look as follows:

Tasks list:
[{Title: hello. Time: 3am}, {Title: meet amy. Time: 5pm}]

EDIT:

Regarding your comment, if you wish to print properties of the class individually, you can simply use the getters of this class. These are autogenerated and in this case have public access.

So you could iterate over all tasks in the list as follows:

    for(task in tasks_list) {
        println(task.title)
        println(task.time)
    }

Which would print out:

hello
3am
meet amy
5pm

Or:

    for(i in 0..tasks_list.size-1) {
        println("Task #: $i")
        println(tasks_list.get(i).title)
        println(tasks_list.get(i).time)
    }

(Note the -1, since the range operator is inclusive) Which would print out:

Task #: 0
hello
3am
Task #: 1
meet amy
5pm

I highly recommend reading some basic documentation (like this) before continuing, as these are very basic things that you would do well to learn before trying to do anything else.

filpa
  • 3,651
  • 8
  • 52
  • 91
  • Thank you so much, It solved my problem. But can I print out the title and the time separated? – Funris Mar 31 '18 at 13:42
  • Updated the answer. Please also consult the official Kotlin [reference](https://kotlinlang.org/docs/reference/) as well as some of the [tutorials](https://kotlinlang.org/docs/tutorials/) on the official language page. – filpa Mar 31 '18 at 14:03
  • Thanks a lot for the resources and for this problem solving! Just thanks! – Funris Apr 01 '18 at 16:32