kotlin klaxon library for json

1.4k Views Asked by At

i'm new to kotlin and decided that best way to learn something is to start using it(So question related more to language than to klaxon library). I'm trying to understand very first snippet from git page of klaxon(https://github.com/cbeust/klaxon). Here it is:

fun parse(name: String) : Any? {
    val cls = Parser::class.java
    return cls.getResourceAsStream(name)?.let { inputStream ->
        return Parser().parse(inputStream)
    }
}

I don't understand why in first case we do

Parser::class.java

and then calling getResource... But then just call

Parser().parse

in second case. What's the difference and why it's like that

P.S Sorry for bad english=)

2

There are 2 best solutions below

0
On BEST ANSWER

Hi Yarick I made easy version of parse function. What I am doing here. I am parsing json api request response as string in function then creating parsing and returning it as JsonObject

Note: Use stringbuilder to create mutable string.

// Json Parsing Object
        fun parse(name: String): JsonObject {
            val parser = Parser()
            val stringBuilder: StringBuilder = StringBuilder(name)
            val json: JsonObject = parser.parse(stringBuilder) as JsonObject
            return json
        }
0
On

Okay, i just figured it out, we need ::class.java because getResourceAsStream is java.lang.Class function. And parse is a member function of Parser class.