logoalt Hacker News

catgirlinspacetoday at 1:38 AM1 replyview on HN

That's pretty much what I was looking for, thank you for sharing! I think that's probably the nicest way I've seen to do it, annoying that Kotlin seems to force you to add it as a child (? idk the word...) of an existing HTML tag, wish you could just import a component or something :(


Replies

t-writescodetoday at 5:07 AM

Kotlin calls those "Extensions" [0], and yeah, they can be pretty annoying. I first learned about them in C# and I had a bunch of frustrations with them, especially when I found some code on StackOverflow or Microsoft's docs and they'd use one of those methods and it just plain wouldn't be there for me because I hadn't downloaded the right nuget package or anything.

I've gotten more used to them and I get why they can be so great now; but there's still some real annoyances with them I just can't shake (like the import problem and the related "where is this code?!" problem)

---

Purely importing a component that's just a simple class, like you can do in Java/Typescript with their jsx and tsx files would be pretty cool, yeah. You could fake it by making a data class and adding a

  fun renderInto(tag: HtmlBlockTag) { ... }
type method, but with how Ktor's Dsl is implemented, you're still going to need to connect it into the giant StringBuilder (or whatever) that the dsl is building to.

To help me get something close to that idea, I tend to dedicate whole files to bigger components and even name the file the same as the root HtmlBlockTag Extension method (like RadioButtonWithLabel.kt if I did it for the earlier one). Those files are great because you can put a bunch of helper methods in the same file and keep it all contained, a lot like a class.

[0] https://kotlinlang.org/docs/extensions.html