Can someone explain why is `Kotlinx.html` consider...
# announcements
d
Can someone explain why is 
Kotlinx.html
 considered type safe?
f
@Dieter Konrad, I don't understand you why
Kotlinx.html
is library for DSL to build HTML or for the DOM. I understand for
type-safety
when the compiler will validate types while compiling. I found this in the documentation https://kotlinlang.org/docs/tutorials/javascript/typesafe-html-dsl.html I'm a noob if there is someone with more experience who can explain us.
n
because you model the DOM using methods and types. every tag must be closed properly (because it uses blocks), preventing you from doing some mistakes like <a><strong></a></strong>. button types are actually enums, so you can't accidentally specify an invalid type. nor can you misspell attributes, like a's href, because it's a property of the anchor type. naturally there are escape hatches so you can create custom tags or attributes if you want, but they're hidden away just enough to make the typical code you're likely to write easy and safe.
👍 2
☝️ 2
also it prevents you from putting invalid elements inside other elements, to some degree
f
@Dieter Konrad, In the documentation there is an example of what Max Aller explains: https://kotlinlang.org/docs/reference/type-safe-builders.html#how-it-works
👍 1
d
So HTML or DIV is then a custom type and it comes from Kotlinx.html library. But my collegue said when I use
buildString { }
from
StringBuilder
it is not typed because it is a string at the end. That is confusing to me. Cause when some html file statically retrieved from server over http it is also just text (string) I think.
f
@Dieter Konrad, I think that it is simple builder because
buildString {}
just run a scope function in the builderAction and return string value.
Copy code
public inline fun buildString(builderAction: StringBuilder.() -> Unit): String {
    contract { callsInPlace(builderAction, InvocationKind.EXACTLY_ONCE) }
    return StringBuilder().apply(builderAction).toString()
}
Type-safe builders create domain-specific languages (DSLs) and hierarchical data structures. PD: If there is someone with more experience to confirm it.
n
I'm not sure how buildString is relevant. ultimately yes, the data is just a string/bytes sent over the wire, but having a typed DSL makes it harder to send an invalid sequence of bytes ;)