{"componentChunkName":"component---src-templates-post-tsx","path":"/posts/2019/07/kotlin-dynamic-typing-kotson/","result":{"data":{"markdownRemark":{"fields":{"slug":"/2019/07/kotlin-dynamic-typing-kotson/"},"frontmatter":{"title":"Simple dynamic typing in Kotlin with Kotson","tag":["kotlin","kotson","dynamic typing","gson","pinned"],"image":"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRI0rk1ieVKhHnaRc3h1vDHHeRJf7Lb8nycLGq_l3FFVXWRyuqa"},"correctedDateEpoch":1563987600000,"html":"<p>Apparently, it is possible to make Kotlin have a very simple dynamic typing, like JavaScript, with a JSON library -- <a href=\"https://github.com/SalomonBrys/Kotson\">Kotson</a>, with some <a href=\"https://github.com/patarapolw/rep2recall-kt/blob/master/src/main/kotlin/rep2recall/json/JsonUtil.kt\">tweaks</a>.</p>\n<!-- excerpt_separator -->\n<p>In JavaScript, there are only very few types, String, Number, Boolean, Null, Undefined, Object; and Array, which is a special kind of object.</p>\n<p>With Kotson, Kotlin and</p>\n<pre><code class=\"language-kotlin\">fun JsonObject.getValueOrNull(key: String): Any? {\n    return if (contains(key)) {\n        get(key).asValue()\n    } else null\n}\n\nfun JsonArray.getValueOrNull(index: Int): Any? {\n    return if (index >= 0 &#x26;&#x26; index &#x3C; size()) {\n        get(index).asValue()\n    } else null\n}\n\nfun JsonElement.asValue(): Any {\n    return try {\n        asDouble\n    } catch (e: Exception) {\n        try {\n            val s = asString\n            if (setOf(\"true\", \"false\").contains(s)) {\n                asBoolean\n            } else s\n        } catch (e: Exception) {\n            this\n        }\n    }\n}\n</code></pre>\n<p>Now, the typing is now limited a very few...</p>\n<ul>\n<li>String -- class java.lang.String</li>\n<li>Number -- class java.lang.Double</li>\n<li>Null -- class com.google.gson.JsonNull</li>\n<li>Boolean -- class java.lang.Boolean</li>\n<li>Array -- class com.google.gson.JsonArray</li>\n<li>Map -- class com.google.gson.JsonObject</li>\n<li>Undefined -- null</li>\n</ul>\n<p>Very simple, isn't it? Also, the comparison is now simpler. For more of how I use it, see <a href=\"https://github.com/patarapolw/rep2recall-kt/blob/master/src/main/kotlin/rep2recall/json/JsonUtil.kt\">https://github.com/patarapolw/rep2recall-kt/blob/master/src/main/kotlin/rep2recall/json/JsonUtil.kt</a></p>"}},"pageContext":{"slug":"/2019/07/kotlin-dynamic-typing-kotson/"}}}