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. By Fernando Sproviero.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Kotlin Playground: Getting Started
10 mins
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.
Getting Started
To open the playground, go to https://play.kotlinlang.org/, where you’ll see the following:
Note there’s already a Hello World program written for you.
Click Run, located on the right, to build and run the code.
You’ll see the following:
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:
You’ll see the following:
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:
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:
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:
The playground has code autocompletion. Choose or type joinToString()
to get the desired output:
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:
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:
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:
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:
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:
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:
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:
- Initialize an HTML Canvas and appending it to the body of the runtime’s
body
. - Set the font and write “Hello Canvas” to the HTML Canvas.
- Draw a red rectangle to the HTML Canvas.
Run it, and you’ll get the following:
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:
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:
- The first test checks that
Family
contains eachPerson
object. - The second test validates that the family name conforms correctly by concatenating each
Person
lastname.
Run these tests and you’ll get the following:
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.