Getting hands dirty with KotlinJs



Although web development hasn't been my thing since I started programming, I was really attracted the way Kotlin does solve things. So I did give a try to KotlinJS.

This is how to set up a KotlinJs page in less than an hour. 

Note: Chose to use the simplest set up without gradle or maven. You are free to chose what you like.

First of all, you start with a new project in your IntelliJ and choose Kotlin -> Javascript.


After that, you can name your project and start. The IDE will generate an empty folder for you.

So to start of, you have lots of options here, for example, you may program the html and css on your own, and than connect the dots with kotlin. Or, you can fully type in Kotlin (as I chose to do it) with this nice library called Kotlinx Html.
Since I'm not using gradle nor maven, I should import it as a JAR (which is not that cool, but for a demo project, no problem) 👎

On with the show. 
So what the app will do? The user inputs a name, and he gets back a Chuck Norris joke with the name inside it.

And after that: 

The code:

I found a nice implementation using the MVP pattern (not sure if it is the right one on the web) here. So I set up the interfaces first.

After that I create the View implementing class and the Presenter implementer class:

Notice the API call is made with XMLHttpRequest, inside the getAsync method. That's the object responsible for API calls. When response successful, we parse the response to our RandomJokeResponse object and let the view handle the rest.


The HTML tags are not constructed as normally thanks to KotlinxHTML, but they are written in Kotlin(DSL).

But the browser doesn't speak Kotlin! The connecting dot.


It certainly needs an HTML file, with some small configuration. On the scripting tags I connect the generated files inside the out directory and libraries that I might include. At that's all sufficient for the browser. Now you may continue to type KOTLIN. 

After that, you are free to create a class whatever the name is, and write the main method, so that the View page will be constructed. Since I'm a spring fan, I add the `Application` suffix: 


Done! You may check the page here:

Name Norris Joke KotlinJS

And full project on:

Name Norris Joke KotlinJS Repository

Conclusion
Kotlin is the language that brought so innovative ways of solving problems. It's growing and improving every day. You may deal nearly everywhere with it: Android, Server-Side, Frontend and even IOS with Kotlin Multiplatform.

Good luck playing with it.