KVision: Creating Webapps with Kotlin

Vishnu Mandole
Globant
Published in
7 min readSep 29, 2023
Source

In this article, we are going to explore the Kotlin web framework, KVision. Frameworks have become an essential part of web development. The standards of web applications are always rising, and so is the complexity of technology needed.

I started looking for a framework for web development that would help me get started quickly. I came across multiple frameworks like Angular, React, Vue, and KVision.

As I’m an Android developer who utilizes Kotlin, I decided to go with KVision for web development because KVision is an object-oriented web framework for Kotlin/JS. It allows you to build modern web applications without any HTML, JavaScript, and CSS knowledge. KVision is built on top of JetBrains’ KotlinJS, which makes Kotlin transpile smoothly to JavaScript. To develop KVision apps, I use Gradle, which manages dependencies and configurations for your application.

Main features

KVision is a cutting-edge web application framework with a range of standout features. Powered by the modern and robust Kotlin programming language, it offers developers a solid foundation for building web applications.

Here are some standout features of KVision:

Uses Kotlin, a compiled and strongly typed programming language

Kotlin, a modern programming language unveiled in 2016 by JetBrains, is a statically typed language celebrated for its impressive practical features and robust tooling support, notably within IntelliJ IDEA.

Easy to use

KVision empowers Android developers to construct contemporary web applications using the Kotlin language, eliminating the need for HTML, CSS, or JavaScript.

Ready-to-use components

It presents an array of nearly 100 pre-designed GUI components, forming a foundational structure for constructing the application’s user interface. Accompanied by a user-friendly and consistent API, it offers access to a multitude of features that are straightforward to learn and implement.

Fullstack

KVision comes with a clever connection setup for popular server-side frameworks like Ktor, Jooby, Spring Boot, Javalin, Vert.x, and Micronaut. This setup lets you create full-stack apps with shared code for things like data and business logic.

Other features

  • Drag & drop support.
  • Type-safe REST connectivity.
  • Integrated JS router.
  • Support for building hybrid mobile applications for Android and iOS with Apache Cordova.
  • Support for building cross-platform desktop applications with Electron.

Creating a Web App with KVision

For the development of our frontend application, we will harness the powerful features of IntelliJ IDE, a robust development environment crafted by JetBrains.

At the heart of our project lies KVision, a modern web framework designed to simplify the creation of interactive web applications. KVision, built on Kotlin, empowers developers with a high-level, expressive, and type-safe API that greatly accelerates web app development.

Create a project

The recommended way to create a new application is either to download and copy the KVision template Or to install the KVision plugin. Once plugins are installed, we can select KVision in the Create new project wizard.

Create new project

Application Structure

We could adhere to the default application structure provided by KVision.

Here we define a Kotlin application class “App” that extends “Application.” The “start” function configures the root element with the “kvapp” identifier and adds a “Hello world” div.

The “main” function initiates the application by invoking “startApplication” with the “App” class and specified modules, providing a robust foundation for your web development project.

For example:

Default Application Structure
  • build.gradle.kts - The build.gradle.kts file is where the building process is defined. It lists all the necessary repositories and all required dependencies.
  • App.kt - The entry point - The starting point of our application. This file consists of the main function for creating the KVision application.
  • Run the App - To run the application with Gradle continuous build, enter:
Gradle Run Command

After Gradle finishes downloading dependencies and building the application, open http://localhost:3000/ in your favorite browser.

You can see the default application after a run

Default Page Load

To make things interesting, let’s make changes in the default app and where we fetch the data from a medium API to show it in a list. Add required dependencies in the gradle file.

Creating a List of components

Here, we have created a list of UI components using DSL builders based on extension functions. These functions facilitate the creation of lists, list items, images, and text blocks for displaying user information and additional details. The code structure is designed for flexibility and reusability, making it a valuable tool for web application developers.

Components.kt

// Function listView that creates an unordered list
// and iterates over the items and invoking the listRow function for each item.
fun Container.listView(state: Post) {
ul(className = "pf-c-data-list") {
state.items?.forEach {
listRow(it)
}
}
}

// function listRow that creates a list item element with element containing user information.
fun Container.listRow(article: ItemX) {
li(className = "videoCard pf-c-data-list__item") li@{
background = Background(Color.name(Col.LAVENDER))
margin = 20.px
padding = 20.px
border = Border(1.px, BorderStyle.SOLID, Color.name(Col.BLACK))
div(className = "pf-l-flex pf-m-align-items-center pf-m-space-items-2xl") {
userInfo(article)
}
}
}

// Function photo that creates image element.
fun Container.photo(itemX: ItemX) {
div(className = "sc-user-photo-75") {
image(src = itemX.thumbnail) {
centered = true

}
}
}

// Function moreInfo that add text block for more info.
fun Container.moreInfo(itemX: ItemX) {
val createdAtFormatted = itemX.pubDate?.let { Date(it).toStringF("MMMM D, YYYY") }
address {
+"${itemX.author}"
br()
+"$createdAtFormatted"
br()
link("More...", "${itemX.link}")
}
}

// Function userInfo that calls the photo and moreInfo functions.
fun Container.userInfo(itemX: ItemX) {
photo(itemX)
moreInfo(itemX)
ul {
li {
link(itemX.title.toString(), "${itemX.link}")
}
}
}

Model class

Here, we have created a different model class for Articles. These model classes are dedicated to handling article data retrieved from API responses. These classes are serialized using Kotlin’s @Serializable annotation, provide a structured representation of the API data.

Models.kt

// Data class for responce from article API
@Serializable
data class Post(
val items: List<ItemX>?,
val status: String?
)

// Data class for item in Post
@Serializable
data class ItemX(
val author: String?,
val categories: List<String>?,
val content: String?,
val description: String?,
val enclosure: Enclosure?,
val guid: String?,
val link: String?,
val pubDate: String?,
val thumbnail: String?,
val title: String?
)

Integrating API and setting response to list in App.kt

This file consists of the main function for creating KVision applications. Initialize the KVision modules directory. Here, we have fetched articles from API, and the response is set to the observable state.

Once the state is updated, the list component will update automatically and display the list of articles.

App.kt

class App : Application() {

private val mCoroutineScope = CoroutineScope(window.asCoroutineDispatcher())
private val articlesList = ObservableValue<Post?>(null)
private val restClient = RestClient()

init {
require("@patternfly/patternfly/patternfly.min.css")
require("@patternfly/patternfly/patternfly-addons.css")
require("css/mybootstrap.css")
loadMediumArticles()
}

//load Medium Articles form medium.com
private fun loadMediumArticles() {
mCoroutineScope.launch {
try {
val searchResult = restClient.call<Post>(ARTICLES_URL).asDeferred().await()
articlesList.value = searchResult
} catch (e: Exception) {
println("Exception $e")
}
}
}

override fun start() {
root("kvapp") {

main {
// label for Articles
label(LABEL_RESOURCES) {
marginLeft = 10.perc
}

// List of Articles
vPanel(spacing = 10, alignItems = AlignItems.CENTER)
{
simplePanel().bind(articlesList) { state ->
width = 80.perc
if (state != null) {
// cardView(state)
listView(state)
}
}
}
}

}
}
}

fun main() {
startApplication(
::App,
module.hot,
CoreModule
)
}

At the end, execute the ./gradlew -t run (on Linux/Mac) command to build, and on successful build, open http://localhost:3000/, and we can see the below output in the browser

Final Output Page

Hurray!

We have developed a front-end web app using KVision without knowledge of HTML, CSS, and JavaScript. It’s simple, isn’t it? I hope you found this article informative and helpful.

Summary

KVision is an open-source web framework created for the Kotlin language. It allows developers to build modern web applications in Kotlin without knowledge of HTML, CSS, or JavaScript, and Kotlin is currently one of the widely used languages for several reasons, including its support for multiple platforms, coroutines, cross-compile capabilities, type safety, and more.

If learning one language allows you to develop apps on multiple platforms, you should give it a try!

Happy Reading :)

Special thanks to Mukund and Prerana Pawar for helping me to write this article.

Thank you 👏🏽

--

--