Swift Apprentice (New Edition)

Go from novice to expert in Swift with hands-on activities in Xcode playgrounds with our freshly-updated book.

Home Android & Kotlin Tutorials

Kotlin Playground: Getting Started

In this Kotlin Playground tutorial, you’ll learn how to use the online tool to write, run and share your code for different targets like JVM, JS and JUNIT.

5/5 3 Ratings

Version

  • Kotlin 1.4, Other, Other

A playground is an online code editor that allows you to write, build, run and share your code with others. It lets you play around with code and test ideas. It’s particularly useful if you’re new to a programming language because you don’t need to install tools, such as a compiler or IDE. In this tutorial, you’ll learn how to use the JetBrains Kotlin Playground.

You’ll learn how to:

  • Run code in the playground using the targets JVM, JS, CANVAS and JUNIT.
  • Share your playground with others.
  • Embed the playground into websites.
Note: This tutorial assumes you have experience developing in Kotlin. If you’re unfamiliar with the language, review our Kotlin for Android tutorial first.

Getting Started

To open the playground, go to https://play.kotlinlang.org/, where you’ll see the following:
hello world

Note there’s already a Hello World program written for you.

Click Run, located on the right, to build and run the code.
Play button

You’ll see the following:
hello world running

Because this is a console app, it will print Hello, world!!! in console output.

Changing the Settings

Playgrounds allow you to configure parts of the environment. In this section, you’ll a look at each configuration and how it affects the playground.

Click Settings on the right:

Settings button

You’ll see the following:

settings

Here’s what these settings mean:

  • Kotlin Version: Choose the version to build your program.
  • Program arguments: Set input arguments for your main function.
  • Target Platform: Select JVM, JS, CANVAS or JUNIT as targets for the code you write.

You’ll start by passing arguments into your app.

Setting Program Arguments

One way to test your Kotlin code is by passing in arguments into your playground.

Input some names separated by spaces:

Input program arguments on the Run configuration screen

Now, change main to receive those arguments:

fun main(args: Array<String>) {
  println("Hello " + args)
}

Run the program, and you’ll see the following output:
hello arguments running

It’s better to show the names separated by commas, right? Do so by adding a dot to the right of the args parameter, and you’ll see the following:
hello arguments autocomplete

The playground has code autocompletion. Choose or type joinToString() to get the desired output:
hello arguments autocomplete join

Your code should look like this:

fun main(args: Array<String>) {
  println("Hello " + args.joinToString())
}

Run the playground again and you’ll see the following output:
hello arguments autocomplete join running

Great! Now that you can pass arguments into your playground, you’ll play around with changing the runtime virtual machine.

Using JVM as the Target Platform

Kotlin has the magical ability to run on different platforms. In this section, you’ll learn what it means to your Kotlin code to change the target platform.

Click Settings again:

target platform jvm

Note that the JVM target platform is already selected.

This is the default target platform. It’s used to run JVM programs, such as the Hello World console app you modified.

In the next sections, you’ll change the target platform to run JavaScript, draw to a Canvas and even run unit tests.

Using JS as the Target Platform

It’s possible to call JavaScript from Kotlin and vice versa.

Kotlin/JS enables server-side web development, such as Node.js, and client-side web development, such as jQuery and React. On these kinds of projects, you’ll want to try a few things related to Kotlin and JavaScript interoperability. The Kotlin Playground can help.

In this section, you’ll change the target platform to JS to run JavaScript from Kotlin.

Select JS as the target platform:
Run configuration screen with JS selected as the target platform

Replace your code with the following:

fun main(args: Array<String>) {
  console.log("Hello " + args.joinToString())
    
  js("alert(\"This is an alert\")")
}

Run your code and you’ll see the phrase This is an alert in your browser as a result of executing the second line:
JS alert

Open the JS console. If you’re using Chrome, press Option-Command-J on macOS or Shift-Control-J on Windows/Linux and you’ll see your list of names as a result of executing the first line:

JS console displaying the list of names

Note: If you try to run this code using the JVM target, you’ll get compilation errors because console and js, as unresolved references, only work when using a JS target.

Using CANVAS as the Target Platform

HTML5 introduced a new element called Canvas, which draws graphics using JavaScript. It lets you create simple static graphics and animations and even render real-time video. You can use Kotlin to interact with Canvas.

The playground allows you to draw in a Canvas. Go to Settings and select CANVAS as the target platform. Remove the program arguments:

Run configuration screen with CANVAS as the target

Replace your code with the following:

import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import kotlin.browser.document
import kotlin.browser.window

// 1
val canvas = initalizeCanvas()
fun initalizeCanvas(): HTMLCanvasElement {
  val canvas = document.createElement("canvas") as HTMLCanvasElement
  val context = canvas.getContext("2d") as CanvasRenderingContext2D
  context.canvas.width  = window.innerWidth.toInt();
  context.canvas.height = window.innerHeight.toInt();
  document.body!!.appendChild(canvas)
  return canvas
}

val context: CanvasRenderingContext2D
  get() {
    return canvas.getContext("2d") as CanvasRenderingContext2D
  }
    
fun main() {
  // 2
  context.font = "30px Arial";
  context.fillText("Hello Canvas", 10.0, 50.0);
  
  // 3  
  context.fillStyle = "#FF0000";
  context.fillRect(200.0, 15.0, 50.0, 50.0);
}

Here’s what you just did:

  1. Initialize an HTML Canvas and appending it to the body of the runtime’s body.
  2. Set the font and write “Hello Canvas” to the HTML Canvas.
  3. Draw a red rectangle to the HTML Canvas.

Run it, and you’ll get the following:

target CANVAS example

You’ve just scratched the surface (pun intended) of what you can do with HTML Canvases. If you’re interested to learn more, checkout the official documentation for more information.

Next you’ll take a look at how to run Kotlin tests from inside the playground.

Using JUNIT as the Target Platform

You also have the option to write unit tests, run them and see which passed and which didn’t. Go to Settings and select JUNIT as the target platform:

Configure settings screen with JUNIT as the target platform

Remove all the code and replace it with the following:

data class Family(val name: String, val people: Array<Person>)
data class Person(val lastname: String) {
  operator fun plus(person: Person): Family {
    return Family(
      lastname + " " + person.lastname, 
      arrayOf(this, this)
    )
  }
}

With this change, you coded Family and Person with a plus operator function that creates a Family when you add two Person objects.

To test these classes, add the following code at the top:

import org.junit.Assert
import org.junit.Test

class PersonTest {
  // 1
  @Test
  fun `Person + Person should create Family containing each Person`() {
    val personOne = Person("Cortazzo")
    val personTwo = Person("Sproviero")
        
    val family = personOne + personTwo
        
    Assert.assertEquals(arrayOf(personOne, personTwo), family.people)
  }

  // 2
  @Test
  fun `Person + Person should create Family concatenating lastnames`() {
    val personOne = Person("Cortazzo")
    val personTwo = Person("Sproviero")
        
    val family = personOne + personTwo
        
    Assert.assertEquals("Cortazzo Sproviero", family.name)
  }
}

Here’s what you just did:

  1. The first test checks that Family contains each Person object.
  2. The second test validates that the family name conforms correctly by concatenating each Person lastname.

Run these tests and you’ll get the following:

tests JUNIT running

One of them failed. By inspecting the plus function, you’ll find the problem is that the function adds itself twice to the array, instead of adding the other person. Fix it by replacing the function with the following code:

operator fun plus(person: Person): Family {
  return Family(
    lastname + " " + person.lastname, 
    arrayOf(this, person)
  )
}

Run the playground again. This time, both tests will pass.

Sharing a Playground Link

This powerful feature allows you to share the code you wrote in the playground with others. This is useful in a few common scenarios:

  • When you code review a pull request, you can use this feature to comment and explain something to someone with runnable code.
  • Others can try your code without installing tools to watch it run.

To share your playground code, press Share:
Share button

You’ll see the following:
Share link

You can share this link with someone else, who will be able to run and check your code.

Embedding a Playground

This next feature lets you embed runnable code directly on your blog or website.

Select Share ▸ Embed to get an iframe that you can paste in your website:

share embed

Choose Share ▸ Medium instead and you’ll get a link to use for embedding in Medium.

Note: As of this writing, the iframe, the link in Medium and navigating to that URL in a browser don’t always work. An issue addressing this problem is open on the repository.

Embedding With a JS Script

An alternative way to embed a playground is to include a JS script in the HTML.

Open a web playground, such as https://codepen.io/pen/, and insert the following:

<script src="https://unpkg.com/kotlin-playground@1" data-selector="code"></script>

Then paste the following code:

fun main() {
  println("Hello Embedded World!!!")
}

You’ll get the following:
web embed Kotlin

Press the green Play button to run it.

You have options to customize the compiler version, args, the target and other features. For more information, go to the Kotlin Playground documentation.

Bear in mind that, because you are writing HTML, you need to escape the HTML entities, including the less-than and greater-than symbols.

For example, to receive the arguments, add the following to main:

fun main(args: Array&lt;String&gt;) {
  println("Hello Embedded World!!! " + args.joinToString())
}

You’ll get the following result:

web embed Kotlin escape

Congratulations! You now know how to use Kotlin Playground! :]

Where To Go From Here?

In this tutorial, you had the chance to familiarize yourself with Kotlin Playground. However, there’s a lot more you can do with it. To learn more, please use the following references:

To understand how the playground works internally or to contribute to the project, check the Kotlin Playground repository.

To learn more about Kotlin, check out examples and the Kotlin Koans, which use embedded playgrounds.

For more information about Kotlin and JavaScript, visit the official Kotlin/JS Overview, where you will find steps on setting up a project and hands-on labs.

Use this Kotlin’s Canvas examples to play around with the Canvas and this HTML Builder to try an interesting way to build HTML using a Kotlin DSL.

To learn more about Canvas, look at the following Mozilla’s tutorial and examples.

I hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!

Average Rating

5/5

Add a rating for this content

3 ratings

More like this

Contributors

Comments