• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

Kotlin JSON object list

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

rainless

Old Member
Joined
Jul 20, 2006
So I have a Comment class contacting JSON objects which I want to store in a list like so:

class Comment(commentJSON: JSONObject) : Serializable {
private lateinit var commentDate: String
lateinit var humanDate: String
lateinit var commentId: String
lateinit var commentBody: String
lateinit var child: List<Comment>
}
So far so good. The problem comes when I want to initialize the "child" List:

init {
try {
commentDate = commentJSON.getString(COMMENT_DATE)
humanDate = convertDateToHumanDate()
commentBody = commentJSON.getString(words)
commentID = commentJSON.getString(cname)
child = listof()
}
}
I'm not really sure I should even be using "listof" and... if so... I have no idea what to put in the parenthesis.
 
I do not program in Kotlin, but looking at their reference page, you can specify a type for the list. Otherwise it will be an empty 'object' list. At least for the languages I use, you almost always want to initialize lists to prevent null reference exceptions.

Code:
child = listof<Comment>()

You haven't specified what you are doing (where is the data coming from? what are you doing with it? where is it going? etc), so I'm not sure how to get more specific than that.
 
I do not program in Kotlin, but looking at their reference page, you can specify a type for the list. Otherwise it will be an empty 'object' list. At least for the languages I use, you almost always want to initialize lists to prevent null reference exceptions.

Code:
child = listof<Comment>()

You haven't specified what you are doing (where is the data coming from? what are you doing with it? where is it going? etc), so I'm not sure how to get more specific than that.

Thanks! You and my friend Gary basically came up with the same solution at the same time (while I was cleaning the electric water boiler... which I am still in the process of doing... :D )

You actually only need listOf() and <Comment> will be assumed (because of the previous lateinit var child: List<Comment> ... Kotlin = Less Typing).

The problem I was having was that I had a typo in a COMPLETELY different file... actually a duplicate line placed in exactly the wrong section... which I don't think I ever would've done. I'm guessing my cat was walking on the keyboard!

But just about anything would've worked for listing the object: listOf(), listOf<Comment>(), emptyList<Comment>()... all that works.

...unless kitty doesn't want it to.

Thanks again! :beer:
 
Back