Web App With Kotlin.js: Getting Started

In this tutorial, you’ll learn how to create a web app using Kotlin.js. This will include manipulating the DOM and fetching data from a server, all in Kotlin! By Ahmed Tarek.

Leave a rating/review
Download materials
Save for later
Share

Since the announcement of official support for Kotlin on Android at Google I/O 2017, the use of Kotlin has massively accelerated within the Android community.

But Kotlin can be used for much more than just Android. You can use Kotlin in place of Java in back-end systems. You can even use Kotlin on the front-end, replacing JavaScript as a web language. Kotlin has the potential to be a true full-stack solution, being in use on the server, in the web browser, and on mobile.

Why Kotlin.js?

So, why would you use Kotlin for web development? Here are a few reasons:

  • Familiarity: If you’re coming from a compiled language like Java, Swift or C#, you’ll find Kotlin very easy to learn — and you might already be familiar with it if you’re an Android developer.
  • Friendly tools: IDEs can’t help you much with JavaScript, while Kotlin comes with first-class IDE support so that you can spot common errors as you type the code.
  • Sharing code between platforms: With Kotlin Multiplatform Projects, you can write the business logic of your app once, and share it across many platforms including your back-end, browser front-end, Android and iOS clients.
  • Interoperability: The ability to call JavaScript code from your Kotlin code is very important. It lets you reuse existing JavaScript code you’ve already written with Kotlin. This interop works in the opposite direction as well. You can call your Kotlin code from JavaScript.
  • JavaScript woes: Kotlin is a perfect choice if you gave up on web development because of common JavaScript issues, such as having to deal with dynamic typing, weird logical comparisons, or prototypes.
Prerequisites: For this tutorial, you need a basic knowledge of web programming and a familiarity with Kotlin and IntelliJ IDEA. If you’re completely new to Kotlin, you might want to check out the Kotlin Apprentice book or the Programming in Kotlin video course first.

Getting Started

You’re going to build a bookstore app for raywenderlich.com. The app will fetch data about the books from a web service, display the book covers with titles, descriptions and prices, as well as a button to open a book’s details page on raywenderlich.com. Here’s what the end product will look like:

End Product

To follow along with this tutorial, you’ll need to use IntelliJ IDEA 2018.2.7 or later (the free Community Edition is good enough), and Kotlin 1.2.61 or later.

Start by downloading the materials for this tutorial using the Download Materials button at the top or bottom of this page. Then fire up IntelliJ IDEA and create a new project.

In the New Project window, select Kotlin from the left side panel and Kotlin/JS on the right. Then, click Next.

New Project Step 1

For the project name, use bookstore. Select a project location, or use the default. Then click Finish.

New Project Step 2

Unzip the materials you’ve downloaded, and from the bookstore-starter folder, copy the index.html and styles.css files to your project’s root folder. The project structure should look like the following:

Project Anatomy

Creating the Main Function

Create a new Kotlin file with the name Main.kt in the src directory and add the main() function as shown below:

fun main(args: Array<String>) {
  println("Hello world!")
}
Note: The app’s main() function can be in any Kotlin file with any name, so using Main.kt as the filename here is not strictly required, but you should only have one main() function in your project.

Next, open the Build menu and click on Build Project to compile your Kotlin code to JavaScript. The IDE will generate a new folder called out in your project’s root folder.

You need to reference two files from this out folder in index.html:

  • kotlin.js: This is a distribution of the Kotlin standard library, implemented in JavaScript.
  • bookstore.js: This is the JavaScript that your own Kotlin code was compiled to.
Note: Both files are already referenced for you within script tags in the starter index.html file, but you may need to check their paths in case you entered a different project name than bookstore.

Finally, open index.html in your browser, and then open the developer console. You should see “Hello World!”, like the following screenshot:

Hello World in Dev Console

Note: Every time you change your Kotlin code, you’ll need to build your project and then refresh the HTML page to see the changes.

Calling JavaScript Code From Kotlin

In the index.html file, inside a <script> tag, you’ll find a JavaScript function called getApiUrl(), which returns the URL you need to fetch the bookstore JSON data from.

<script>
function getApiUrl(){
  return "https://gist.githubusercontent.com/tarek360/4578e33621011e18829bad0c8d1c8cdf/raw/06d185bebc3e14a56dfa85f53288daddd4ff6a2b/books.json";
}
</script>

There are many ways to access a JavaScript function or variable from your Kotlin code. One of them is by using the js() function, which allows you to pass native JavaScript code as a string.

Add the following line of code to the Main.kt file, outside of the main() function.

val API_URL = js("getApiUrl()") as String

Here, you pass the string "getApiUrl()" to the js() function. Since the getApiUrl() function always returns a string, you can cast it safely to a Kotlin String, and store it in a Kotlin value.

Now, update the main() function to print the value of the API_URL property instead of “Hello world!”.

fun main(args: Array<String>) {
  println(API_URL)
}

Build the project and refresh index.html in your browser. You should see the value of the API_URL variable printed to the console, like the following screenshot:

API URL in Dev Console

Now, you have the URL saved in the API_URL value, which you’ll use later.
Finally, clear the main() function’s body to get ready for what comes next.

Representing Books

RW Books

To fetch book data from the server and present it on the UI, you need to create a new Kotlin class to represent a single book. Create a file named Book.kt in the src folder and place this data class in it:

data class Book(val title: String,
                val price: String,
                val description: String,
                val url: String,
                val coverUrl: String)

Every book has a title, price, description, a URL for its details page on raywenderlich.com, and a cover image URL.

Ahmed Tarek

Contributors

Ahmed Tarek

Author

Márton Braun

Tech Editor

Ryan Dube

Editor

Pankaj Kumar

Illustrator

Joe Howard

Final Pass Editor

Eric Soto

Team Lead

Over 300 content creators. Join our team.