Appendix B. Documenting Kotlin code

This appendix covers writing documentation comments for Kotlin code and generating API documentation for Kotlin modules.

B.1. Writing Kotlin documentation comments

The format used to write documentation comments for Kotlin declarations is similar to Java’s Javadoc and is called KDoc. Just as in Javadoc, KDoc comments begin with /** and use tags starting with @ to document specific parts of a declaration. The key difference between Javadoc and KDoc is that the format used to write the comments themselves is Markdown ( https://daringfireball.net/projects/markdown ) rather than HTML. To make writing documentation comments easier, KDoc supports a number of additional conventions to refer to documentation elements such as function parameters.

Here’s a simple example of a KDoc comment for a function.

Listing B.1. Using a KDoc comment

B.2. generating api documentation.

kotlin how to write documentation

Documenting Kotlin Code for Android Using KDoc and Dokka

Learn how to use KDoc to document your Kotlin code and generate beautiful-looking documentation pages using Dokka. By Rajdeep Singh .

Sign up/Sign in

With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!

Already a member of Kodeco? Sign in

Getting Started

Understanding the project structure, making a case for documentation, going beyond code comments, learning from examples, introducing kdoc.

  • Defining Block Tags
  • Documenting Modules and Packages
  • Introducing Dokka
  • Integrating Dokka
  • Generating Documentation
  • Customizing Dokka
  • Adding External Documentation
  • Customizing Member Visibility
  • Customizing Module and Package Pages
  • Using Custom Assets
  • Where to Go From Here?

Good documentation can make a developer prefer one library over others.

Documentation comes in many forms. From simple comments that live alongside the code to complex websites like the Android Developer documentation that cover things like platform APIs, build tools, samples, etc., it’s all documentation.

In this article, you’ll learn:

  • How documentation can help you to improve the quality of your projects.
  • To use KDoc to document your Kotlin code.
  • To use Dokka to generate great-looking documentation quickly and easily.
  • How to customize Dokka to your liking.

You’ll work on an Android library project called notktx and generate customized documentation for it.

The major target audience for libraries is usually other developers, so documenting a library project can be a great way to understand how to go about documenting codebases. Making it easy for other developers to use your project is a challenging but rewarding task — and good documentation plays a major role in it.

By the end of this article, you’ll have documentation generated in HTML for the notktx project. Here’s what it will look like:

Documentation for notktx project in HTML format

This article assumes you have previous experience developing for Android in Kotlin. If you’re unfamiliar with Kotlin, take a look at this Introduction to Kotlin for Android article. If you’re also new to Android development, check out these Getting Started With Android tutorials.

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

Open Android Studio and click Open an existing Android Studio project .

Navigate to the starter project directory you downloaded and click Open .

Take some time to familiarize yourself with the project.

The project implements extensions for Android widgets to help users by handling boilerplate code for various use cases.

You’ll find these three modules in the starter project:

  • app : An app module that shows sample usage of the library.
  • core : A library module that provides extensions for Android framework-related APIs and widgets.
  • utilities : Another library module that provides extensions that use third-party libraries to work.

Now that you have an overview of the files in this project, build and run. You’ll see a screen like this:

Starter project screenshot

Without realizing it, you might already be documenting your code. The code snippets below show different ways to write an Extension Function for SharedPreferences to add key-value pairs and commit the changes.

Choosing descriptive names for variables and functions is the first step toward a well-documented codebase. In the example above, it’s much easier to understand what’s going on in the second function than in the first one.

You can go even further and add comments describing the function. For example:

When you document your code, you help new users and contributors to trust and understand your project better. In a professional setting, good documentation helps new developers on your team — as well as on other teams — to get started with your project quickly.

Documentation also helps you. Going through your old codebase line by line after some time away can be time-consuming. So by documenting it, you’re helping your future self, too.

Documentation doesn’t have a fixed definition — but it goes way beyond comments. You can get as creative as you want while documenting your code, as long as it helps others to understand your code.

There are many ways to document a project:

  • Hosting API references online.
  • Writing a small book to give users an overview.
  • Recording screencast videos walking users through major parts of the code.
  • …and the list goes on.

In the Android world, Glide and Retrofit are quite famous for loading images and making network calls — and their documentation pages are really good.

Glide library documentation page

Both of them try to get readers started as quickly as possible with minimal setup, but they provide in-depth API references for the advanced readers, too.

Golang and Kotlin provide code playgrounds to let users directly interact with sample programs. Check those out here and here .

Another super-creative example of documentation is this YouTube channel by Andreas Kling . He regularly uploads screencasts about his project SerenityOS .

All that to say, there isn’t just one way to define documentation. In the next few sections, you’ll see how to use KDoc and Dokka to ease the process of generating documentation for your Kotlin/Java/Android projects.

If you’re coming from a Java background and have used JavaDoc before, you’ll feel right at home with KDoc . It uses JavaDoc’s syntax and adds support for Kotlin-specific constructs.

For those who haven’t used JavaDoc before, it’s a tool by Oracle that generates HTML pages from the Java source code files. The language format it uses for documenting is also named JavaDoc.

JavaDoc parses the source files for class/method declarations along with the comments written in JavaDoc format to add descriptions for those elements.

KDoc uses JavaDoc’s syntax, but unlike JavaDoc, it isn’t a tool to generate the HTML pages. Dokka generates the documentation from KDoc comments.

Open MainActivity.kt in the starter code and replace TODO:1 with the code snippet below:

Also, replace TODO:2 with this snippet:

The first snippet is a plain multiline comment, and the second one is a KDoc documentation comment. It uses a forward slash followed by two asterisks instead of one.

Each line of a KDoc comment other than the first and the last one starts with an optional asterisk. Dokka ignores those asterisks.

Dokka recognizes KDoc comments only when they come immediately before a class/method/field definition — so they’re ignored when placed inside the body of a method or anywhere else.

The format of a KDoc comment consists of an initial description followed by a series of block tags. You’ll learn about the block tags in the next section.

The first paragraph of any KDoc comment before a blank line is the summary description of the element, and the text that follows is the detailed description .

All videos. All books. One low price.

A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.

  • Español – América Latina
  • Português – Brasil

Build Your First Android App in Kotlin

1. welcome.

6cba94311109e72f.png

In this codelab, you'll learn how to build and run your first Android app in the Kotlin programming language. (If you're looking for the Java version of this codelab , you can go here .) Kotlin is a statically typed programming language that runs on the JVM and is completely interoperable with the Java programming language. Kotlin is an officially supported language for developing Android apps, along with Java.

What you must know already

This codelab is written for programmers and assumes that you know either the Java or Kotlin programming language. If you are an experienced programmer and adept at reading code, you will likely be able to follow this codelab, even if you don't have much experience with Kotlin.

What you'll learn

  • How to use Android Studio to build your app.
  • How to run your app on a device or in the emulator.
  • How to add interactive buttons.
  • How to display a second screen when a button is pressed.

Use Android Studio and Kotlin to write Android apps

You write Android apps in Kotlin or in the Java programming language using an IDE called Android Studio. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development.

To work through this codelab, you will need a computer that can run Android Studio 3.6 or higher (or already has Android Studio 3.6 or higher installed).

2. Install Android Studio

You can download Android Studio 3.6 from the Android Studio page.

Android Studio provides a complete IDE, including an advanced code editor and app templates. It also contains tools for development, debugging, testing, and performance that make it faster and easier to develop apps. You can use Android Studio to test your apps with a large range of preconfigured emulators, or on your own mobile device. You can also build production apps and publish apps on the Google Play store.

Android Studio is available for computers running Windows or Linux, and for Macs running macOS. The OpenJDK (Java Development Kit) is bundled with Android Studio.

The installation is similar for all platforms. Any differences are noted below.

  • Navigate to the Android Studio download page and follow the instructions to download and install Android Studio .
  • Accept the default configurations for all steps, and ensure that all components are selected for installation.
  • After the install is complete, the setup wizard downloads and installs additional components, including the Android SDK. Be patient, because this process might take some time, depending on your internet speed.
  • When the installation completes, Android Studio starts, and you are ready to create your first project.

3. Task: Create your first project

In this step, you will create a new Android project for your first app. This simple app displays the string "Hello World" on the screen of an Android virtual or physical device.

Here's what the finished app will look like:

72c7e6d2960f4faa.png

  • How to create a project in Android Studio.
  • How to create an emulated Android device.
  • How to run your app on the emulator.
  • How to run your app on your own physical device, if you have one.

Step 1: Create a new project

  • Open Android Studio.
  • In the Welcome to Android Studio dialog, click Start a new Android Studio project .

53dd04173e9ada63.png

  • Give your application a name, such as My First App .
  • Make sure the Language is set to Kotlin .
  • Leave the defaults for the other fields.
  • Click Finish .

After these steps, Android Studio:

  • Creates a folder for your Android Studio project. This is usually in a folder called AndroidStudioProjects below your home directory.
  • Builds your project (this may take a few moments). Android Studio uses Gradle as its build system. You can follow the build progress at the bottom of the Android Studio window.
  • Opens the code editor showing your project.

Step 2: Get your screen set up

When your project first opens in Android Studio, there may be a lot of windows and panes open. To make it easier to get to know Android Studio, here are some suggestions on how to customize the layout.

97a3da610c1eede7.png

  • Depending on the size of your screen, consider resizing the pane on the left showing the project folders to take up less space.

At this point, your screen should look a bit less cluttered, similar to the screenshot shown below.

70183da1f878e11a.png

Step 3: Explore the project structure and layout

ecabcf48b6f7b9a1.png

Based on you selecting the Basic Activity template for your project, Android Studio has set up a number of files for you. You can look at the hierarchy of the files for your app in multiple ways, one of which is in Project view (2) . Project view shows your files and folders structured in a way that is convenient for working with an Android project. (This does not always match the file hierarchy! To see the file hierarchy, choose the Project files view by clicking (3) .)

  • Double-click the app (1) folder to expand the hierarchy of app files. (See (1) in the screenshot.)
  • If you click Project (2) , you can hide or show the Project view.
  • The current Project view selection is Project > Android .

In the Project > Android view you see three or four top-level folders below your app folder: manifests , java , java (generated) and res . You may not see java (generated) right away.

  • Expand the manifests folder.

This folder contains AndroidManifest.xml . This file describes all the components of your Android app and is read by the Android runtime system when your app is executed. 2. Expand the java folder. All your Kotlin language files are organized here; Android projects keep all Kotlin language files in this folder, together with any Java sources. The java folder contains three subfolders:

com.example.myfirstapp (or the domain name you have specified) : This folder contains the Kotlin source code files for your app.

com.example.myfirstapp (androidTest): This folder is where you would put your instrumented tests, which are tests that run on an Android device. It starts out with a skeleton test file.

com.example.myfirstapp (test): This folder is where you would put your unit tests. Unit tests don't need an Android device to run. It starts out with a skeleton unit test file. 3. Expand the res folder. This folder contains all the resources for your app, including images, layout files, strings, icons, and styling. It includes these subfolders:

drawable : All your app's images will be stored in this folder.

layout : This folder contains the UI layout files for your activities. Currently, your app has one activity that has a layout file called activity_main.xml . It also contains content_main.xml , fragment_first.xml , and fragment_second.xml .

menu: This folder contains XML files describing any menus in your app.

mipmap : This folder contains the launcher icons for your app.

navigation: This folder contains the navigation graph, which tells Android Studio how to navigate between different parts of your application.

values : Contains resources, such as strings and colors, used in your app.

Step 4: Create a virtual device (emulator)

In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device (or emulator) that simulates the configuration for a particular type of Android device.

The first step is to create a configuration that describes the virtual device.

1ef215721ed1bd47.png

  • Click +Create Virtual Device . (If you have created a virtual device before, the window shows all of your existing devices and the +Create Virtual Device button is at the bottom.) The Select Hardware window shows a list of pre-configured hardware device definitions.
  • Choose a device definition, such as Pixel 2 , and click Next . (For this codelab, it really doesn't matter which device definition you pick).
  • In the System Image dialog, from the Recommended tab, choose the latest release. (This does matter.)
  • If a Download link is visible next to a latest release, it is not installed yet, and you need to download it first. If necessary, click the link to start the download, and click Next when it's done. This may take a while depending on your connection speed.
  • In the next dialog box, accept the defaults, and click Finish .

The AVD Manager now shows the virtual device you added.

  • If the Your Virtual Devices AVD Manager window is still open, go ahead and close it.

Step 5: Run your app on your new emulator

609c3e4473493202.png

  • In Run > Select Device , under Available devices , select the virtual device that you just configured. A dropdown menu also appears in the toolbar.

b1215d5cf034b077.png

The emulator starts and boots just like a physical device. Depending on the speed of your computer, this may take a while. You can look in the small horizontal status bar at the very bottom of Android Studio for messages to see the progress.

Once your app builds and the emulator is ready, Android Studio uploads the app to the emulator and runs it. You should see your app as shown in the following screenshot.

89960f5a856e1aa7.png

Step 6: Run your app on a device (if you have one)

What you need:

  • An Android device such as a phone or tablet.
  • A data cable to connect your Android device to your computer via the USB port.
  • If you are using a Linux or Windows OS, you may need to perform additional steps to run your app on a hardware device. Check the Run Apps on a Hardware Device documentation. On Windows, you may need to install the appropriate USB driver for your device. See OEM USB Drivers .

Run your app on a device

To let Android Studio communicate with your device, you must turn on USB Debugging on your Android device.

On Android 4.2 and higher, the Developer options screen is hidden by default. To show Developer options and enable USB Debugging:

  • On your device, open Settings > About phone and tap Build number seven times.
  • Return to the previous screen ( Settings ). Developer options appears at the bottom of the list. Tap Developer options .
  • Enable USB Debugging .

Now you can connect your device and run the app from Android Studio.

  • Connect your device to your development machine with a USB cable. On the device, you might need to agree to allow USB debugging from your development device.
  • Select your device, and click OK . Android Studio installs the app on your device and runs it.

Troubleshooting

If you're stuck, quit Android Studio and restart it.

If Android Studio does not recognize your device, try the following:

  • Disconnect your device from your development machine and reconnect it.
  • Restart Android Studio.

If your computer still does not find the device or declares it "unauthorized":

  • Disconnect the device.
  • On the device, open Settings->Developer Options .
  • Tap Revoke USB Debugging authorizations .
  • Reconnect the device to your computer.
  • When prompted, grant authorizations.

If you are still having trouble, check that you installed the appropriate USB driver for your device. See the Using Hardware Devices documentation .

Check the troubleshooting section in the Android Studio documentation .

Step 7: Explore the app template

When you created the project and selected Basic Activity , Android Studio set up a number of files, folders, and also user interface elements for you, so you can start out with a working app and major components in place. This makes it easier to build your application.

791b06443568c703.png

Later in this codelab, you'll look at the Next button and modify the way it looks and what it does.

4. Task: Explore the layout editor

Generally, each screen in your Android app is associated with one or more fragments . The single screen displaying "Hello first fragment" is created by one fragment, called FirstFragment . This was generated for you when you created your new project. Each visible fragment in an Android app has a layout that defines the user interface for the fragment. Android Studio has a layout editor where you can create and define layouts.

Layouts are defined in XML . The layout editor lets you define and modify your layout either by coding XML or by using the interactive visual editor.

Every element in a layout is a view. In this task, you'll explore some of the panels in the layout editor, and you'll learn how to change properties of views.

  • How to use the layout editor.
  • How to set property values.
  • How to add string resources.
  • How to add color resources.

Step 1: Open the layout editor

bb7b4fe5af80859d.png

  • Double-click fragment_first.xml .

356e0f1c3bbc6e40.png

On the left is a Palette of views you can add to your app.

Below that is a Component Tree showing the views currently in this file, and how they are arranged in relation to each other.

In the center is the Design editor, which shows a visual representation of what the contents of the file will look like when compiled into an Android app. You can view the visual representation, the XML code, or both.

c60f285cb7fbc306.png

  • Try selecting the different modes. Depending on your screen size and work style, you may prefer switching between Code and Design , or staying in Split view. If your Component Tree disappears, hide and show the Palette .

32d3075ed7f5c02c.png

  • At the lower right of the Design editor you see + and - buttons for zooming in and out. Use these buttons to adjust the size of what you see, or click the zoom-to-fit button so that both panels fit on your screen.

a7d0a08766682f9.png

The Design layout on the left shows how your app appears on the device. The Blueprint layout , shown on the right, is a schematic view of the layout.

6572c0c05460eafd.png

Depending on the size of your screen and your preference, you may wish to only show the Design view or the Blueprint view, instead of both.

c40138d924cedb8f.png

  • Use the device menu to view the layout on different devices. (This is extremely useful for testing!)

46754977c9c3d6c9.png

On the right is the Attributes panel. You'll learn about that later.

Step 2: Explore and resize the Component Tree

  • In fragment_first.xml , look at the Component Tree . If it's not showing, switch the mode to Design instead of Split or Code .

855789e5c4867c8f.png

The Component Tree closes. 4. Bring back the Component Tree by clicking the vertical label Component Tree on the left.

35c14a27fd2ce30a.png

Step 3: Explore view hierarchies

  • In the Component Tree , notice that the root of the view hierarchy is a ConstraintLayout view.

Every layout must have a root view that contains all the other views. The root view is always a view group , which is a view that contains other views. A ConstraintLayout is one example of a view group. 2. Notice that the ConstraintLayout contains a TextView , called textview_first and a Button , called button_first .

506cf77387f00782.png

  • If the code isn't showing, switch to Code or Split view using the icons in the upper right corner.
  • In the XML code, notice that the root element is <androidx.constraintlayout.widget.ConstraintLayout> . The root element contains a <TextView> element and a <Button> element.

Step 4: Change property values

  • In the code editor, examine the properties in the TextView element.
  • Click on the string in the text property, and you'll notice it refers to a string resource, hello_first_fragment .
  • Right-click on the property and click Go To > Declaration or Usages

values/strings.xml opens with the string highlighted.

  • Change the value of the string property to Hello World! .
  • Switch back to fragment_first.xml .

19cfd9f54f58b379.png

  • Run the app to see the change you made in strings.xml . Your app now shows "Hello World!".

d2103406630c3527.png

Step 5: Change text display properties

  • With textview_first still selected in the Component Tree , in the layout editor, in the list of attributes, under Common Attributes , expand the textAppearance field. (You may need to scroll down to find it.)

37c72a9385dab52d.png

  • Change some of the text appearance properties. For example, change the font family, increase the text size, and select bold style. (You might need to scroll the panel to see all the fields.)
  • Change the text color. Click in the textColor field, and enter g .

A menu pops up with possible completion values containing the letter g. This list includes predefined colors.

39597ff5cf9661da.png

  • Select @android:color/darker_gray and press Enter .

Below is an example of the textAppearance attributes after making some changes.

8751426a21281f94.png

  • Look at the XML for the TextView . You see that the new properties have been added.
  • Run your app again and see the changes applied to your Hello World! string

c715d9230068d0f8.png

Step 6: Display all attributes

  • In the Attributes panel, scroll down until you find All Attributes .

6e28336e8d85fa14.png

  • Scroll through the list to get an idea of the attributes you could set for a TextView .

5. Task: Add color resources

So far you have learned how to change property values. Next, you will learn how to create more resources like the string resources you worked with earlier. Using resources enables you to use the same values in multiple places, or to define values and have the UI update automatically whenever the value is changed.

  • How resources are defined.
  • Adding and using color resources.
  • The results of changing layout height and width.

Step 1: Add color resources

First, you'll learn how to add new color resources.

Change the text color and background of the TextView

  • In the Project panel on the left, double-click on res > values > colors.xml to open the color resource file.

8fa53d358e4a9813.png

The colors.xml file opens in the editor. So far, three colors have been defined. These are the colors you can see in your app layout (for example, purple for the app bar).

  • Go back to fragment_first.xml so you can see the XML code for the layout.
  • Add a new property to the TextView called android:background , and start typing to set its value to @color . You can add this property anywhere inside the TextView code.

A menu pops up offering the predefined color resources:

f08dbc2b6d4fc39.png

  • Choose @color/colorPrimaryDark.
  • Change the property android:textColor and give it a value of @android:color/white .

The Android framework defines a range of colors, including white, so you don't have to define white yourself. 6. In the layout editor, you can see that the TextView now has a dark blue or purple background, and the text is displayed in white.

c0c2141dd09c7ea7.png

Step 2: Add a new color to use as the screen background color

  • Back in colors.xml , create a new color resource called screenBackground:

A Color can be defined as 3 hexadecimal numbers (#00-#FF, or 0-255) representing the red, blue, and green (RGB) components. The color you just added is yellow. Notice that the colors corresponding to the code are displayed in the left margin of the editor.

e2749d2e88ddf4a3.png

Note that a color can also be defined including an alpha value (#00-#FF), which represents the transparency (#00 = 0% = fully transparent, #FF = 100% = fully opaque). When included, the alpha value is the first of 4 hexadecimal numbers (ARGB).

The alpha value is a measure of transparency. For example, #88FFEE58 makes the color semi-transparent, and if you use #00FFEE58, it's fully transparent and disappears from the left-hand bar.

  • Go back to fragment_first.xml .

98c54173559bb461.png

  • In the Attributes panel, select the background property and press Enter . Type "c" in the field that appears.
  • In the menu of colors that appears, select @color/screenBackground . Press Enter to complete the selection.

4ad182142b7286e6.png

  • Click on the yellow patch to the left of the color value in the background field.

825da5a9b24ce5ff.png

  • Feel free to change the value of the screenBackground color, but make sure that the final color is noticeably different from the colorPrimary and colorPrimaryDark colors.

Step 3: Explore width and height properties

Now that you have a new screen background color, you will use it to explore the effects of changing the width and height properties of views.

  • In fragment_first.xml , in the Component Tree , select the ConstraintLayout .

3b78c455704d36b8.png

The layout_width and layout_height properties are both set to match_parent . The ConstraintLayout is the root view of this Fragment , so the "parent" layout size is effectively the size of your screen.

  • Notice that the entire background of the screen uses the screenBackground color.

6cda01dc20388d55.png

  • Select textview_first . Currently the layout width and height are wrap_content , which tells the view to be just big enough to enclose its content (plus padding)
  • Change both the layout width and layout height to match_constraint , which tells the view to be as big as whatever it's constrained to.

The width and height show 0dp , and the text moves to the upper left, while the TextView expands to match the ConstraintLayout except for the button. The button and the text view are at the same level in the view hierarchy inside the constraint layout, so they share space.

b8740b4dc43dc9c4.png

  • Explore what happens if the width is match_constraint and the height is wrap_content and vice versa. You can also change the width and height of the button_first.
  • Set both the width and height of the TextView and the Button back to wrap_content .

6. Task: Add views and constraints

In this task, you will add two more buttons to your user interface, and update the existing button, as shown below.

94e4cf7f4bb5264b.png

  • How to add new views to your layout.
  • How to constrain the position of a view to another view.

Step 1: View constraint properties

  • In fragment_first.xml , look at the constraint properties for the TextView .

These properties define the position of the TextView . Read them carefully.

You can constrain the top, bottom, left, and right of a view to the top, bottom, left, and right of other views.

  • Select textview_first in the Component Tree and look at the Constraint Widget in the Attributes panel.

938d3a1c319e1f.png

Step 2: Add buttons and constrain their positions

To learn how to use constraints to connect the positions of views to each other, you will add buttons to the layout. Your first goal is to add a button and some constraints, and change the constraints on the Next button.

  • Notice the Palette at the top left of the layout editor. Move the sides if you need to, so that you can see many of the items in the palette.

47603a2d993c378b.png

Step 3: Add a constraint to the new button

You will now constrain the top of the button to the bottom of the TextView .

  • Move the cursor over the circle at the top of the Button .

d692d553fdb8d06c.png

  • Click and drag the circle at the top of the Button onto the circle at the bottom of the TextView .

9e7bcb556cd2b58c.png

The Button moves up to sit just below the TextView because the top of the button is now constrained to the bottom of the TextView .

7aa4fd347b3ebde9.png

  • Take a look at the Constraint Widget in the Layout pane of the Attributes panel. It shows some constraints for the Button , including Top -> BottomOf textView .
  • Take a look at the XML code for the button. It now includes the attribute that constrains the top of the button to the bottom of the TextView .
  • You may see a warning, " Not Horizontally Constrained ". To fix this, add a constraint from the left side of the button to the left side of the screen.
  • Also add a constraint to constrain the bottom of the button to the bottom of the screen.

Before adding another button, relabel this button so things are a little clearer about which button is which.

  • Click on the button you just added in the design layout.
  • Look at the Attributes panel on the right, and notice the id field.
  • Change the id from button to toast_button .

Step 4: Adjust the Next button

You will adjust the button labeled Next , which Android Studio created for you when you created the project. The constraint between it and the TextView looks a little different, a wavy line instead of a jagged one, with no arrow. This indicates a chain , where the constraints link two or more objects to each other, instead of just one to another. For now, you'll delete the chained constraints and replace them with regular constraints.

To delete a constraint:

1f8c250ad15873d5.png

  • Or click on one of the constrained views, then right-click on the constraint and select Delete from the menu.
  • Or in the Attributes panel, move the cursor over the circle for the constraint until it shows an x, then click it.

7f4931356c145bab.png

If you delete a constraint and want it back, either undo the action, or create a new constraint.

Step 5: Delete the chain constraints

  • Click on the Next button, and then delete the constraint from the top of the button to the TextView .
  • Click on the TextView , and then delete the constraint from the bottom of the text to the Next button.

Step 6: Add new constraints

  • Constrain the right side of the Next button to the right of the screen if it isn't already.
  • Delete the constraint on the left side of the Next button.
  • Now constrain the top and bottom of the Next button so that the top of the button is constrained to the bottom of the TextView and the bottom is constrained to the bottom of the screen. The right side of the button is constrained to the right side of the screen.
  • Also constrain the TextView to the bottom of the screen.

It may seem like the views are jumping around a lot, but that's normal as you add and remove constraints.

7fb69c02100a87f6.png

Step 7: Extract string resources

  • In the fragment_first.xml layout file, find the text property for the toast_button button.
  • Notice that the text "Button" is directly in the layout field, instead of referencing a string resource as the TextView does. This will make it harder to translate your app to other languages.
  • To fix this, click the highlighted code. A light bulb appears on the left.

47544075e3e5ecdb.png

  • In the dialog box that appears, change the resource name to toast_button_text and the resource value to Toast and click OK .

8fa866598929c1b4.png

  • Notice that the value of the android:text property has changed to @string/toast_button_text .
  • Go to the res > values > strings.xml file. Notice that a new string resource has been added, named toast_button_text .

73c7729f2d8329df.png

You now know how to create new string resources by extracting them from existing field values. (You can also add new resources to the strings.xml file manually.) And you know how to change the id of a view.

Step 8: Update the Next button

The Next button already has its text in a string resource, but you'll make some changes to the button to match its new role, which will be to generate and display a random number.

  • As you did for the Toast button, change the id of the Next button from button_first to random_button in the Attributes panel.

434e77fabe53b6a3.png

  • In strings.xml , right-click on the next string resource.
  • Select Refactor > Rename... and change the name to random_button_text .
  • Click Refactor to rename your string and close the dialog.
  • Change the value of the string from Next to Random .
  • If you want, move random_button_text to below toast_button_text .

Step 9: Add a third button

Your final layout will have three buttons, vertically constrained the same, and evenly spaced from each other.

7e6529faadd88569.png

  • In fragment_first.xml , add another button to the layout, and drop it somewhere between the Toast button and the Random button, below the TextView .
  • Add vertical constraints the same as the other two buttons. Constrain the top of the third button to the bottom of TextView ; constrain the bottom of the third button to the bottom of the screen.
  • Add horizontal constraints from the third button to the other buttons. Constrain the left side of the third button to the right side of the Toast button; constrain the right side of the third button to the left side of the Random button.

Your layout should look something like this:

7588895a67295422.png

  • Examine the XML code for fragment_first.xml . Do any of the buttons have the attribute app:layout_constraintVertical_bias ? It's OK if you do not see that constraint.

The "bias" constraints allows you to tweak the position of a view to be more on one side than the other when both sides are constrained in opposite directions . For example, if both the top and bottom sides of a view are constrained to the top and bottom of the screen, you can use a vertical bias to place the view more towards the top than the bottom.

Here is the XML code for the finished layout. Your layout might have different margins and perhaps some different vertical or horizontal bias constraints.The exact values of the attributes for the appearance of the TextView might be different for your app.

Step 10: Get your UI ready for the next task

The next task is to make the buttons do something when they are pressed. First, you need to get the UI ready.

  • Change the text of the TextView to show 0 (the number zero).
  • Change the text alignment to center.

7084faa39a820830.png

  • Change the id of the last button you added, button2 , to count_button in the Attributes panel in the design editor.
  • In the XML, extract the string resource to count_button_text and set the value to Count.

bbe0bcab6903ea27.png

The buttons should now have the following text and ids:

  • Run the app.

Step 11: Fix errors if necessary

c01516073934ed58.png

The errors occur because the buttons have changed their id and now these constraints are referencing non-existent views.

If you have these errors, fix them by updating the id of the buttons in the constraints that are underlined in red.

7. Task: Update the appearance of the buttons and the TextView

Your app's layout is now basically complete, but its appearance can be improved with a few small changes.

Step 1: Add new color resources

  • In colors.xml , change the value of screenBackground to #2196F3 , which is a blue shade in the Material Design palette .
  • Add a new color named buttonBackground . Use the value #BBDEFB , which is a lighter shade in the blue palette.

Step 2: Add a background color for the buttons

  • In the layout, add a background color to each of the buttons. (You can either edit the XML in fragment_first.xml or use the Attributes panel, whichever you prefer.)

Step 3: Change the margins of the left and right buttons

  • Give the Toast button a left (start) margin of 24dp and give the Random button a right (end) margin of 24dp. (Using start and end instead of left and right makes these margins work for all language directions.)

81c294a2cf04b801.png

Step 4: Update the appearance of the TextView

  • Remove the background color of the TextView , either by clearing the value in the Attributes panel or by removing the android:background attribute from the XML code.

When you remove the background, the view background becomes transparent. 2. Increase the text size of the TextView to 72sp.

  • Change the font-family of the TextView to sans-serif (if it's not already).
  • Add an app:layout_constraintVertical_bias property to the TextView , to bias the position of the view upwards a little so that it is more evenly spaced vertically in the screen. Feel free to adjust the value of this constraint as you like. (Check in the design view to see how the layout looks.)

7c73e04dc2f35d00.png

  • Make sure the layout_width is wrap_content , and the horizontal bias is 50 ( app:layout_constraintHorizontal_bias="0.5" in XML).

Step 5: Run your app

If you implemented all the updates, your app will look like the following figure. If you used different colors and fonts, then your app will look a bit different.

214cfb8299ed8d36.png

8. Task: Make your app interactive

You have added buttons to your app's main screen, but currently the buttons do nothing. In this task, you will make your buttons respond when the user presses them.

First you will make the Toast button show a pop-up message called a toast . Next you will make the Count button update the number that is displayed in the TextView .

  • How to find a view by its ID.
  • How to add click listeners for a view.
  • How to set and get property values of a view from your code.

Step 1: Enable auto imports

To make your life easier, you can enable auto-imports so that Android Studio automatically imports any classes that are needed by the Kotlin code.

  • In Android Studio, open the settings editor by going to File > Other Settings > Preferences for New Projects . (Or Settings for New Projects . The text varies between versions of Android Studio.)
  • Select Auto Import . In the Java and Kotlin sections, make sure Add Unambiguous Imports on the fly is checked.

5507aa63b0db10d5.png

Step 2: Show a toast

In this step, you will attach a Kotlin method to the Toast button to show a toast when the user presses the button. A toast is a short message that appears briefly at the bottom of the screen.

b3d6daf5bb6784d9.png

  • Open FirstFragment.kt . ( app > java > com.example.android.myfirstapp > FirstFragment ).

This class has only two methods, onCreateView() and onViewCreated() . These methods execute when the fragment starts.

As mentioned earlier, the id for a view helps you identify that view distinctly from other views. Using the findViewByID() method, your code can find the random_button using its id, R.id.random_button . 2. Take a look at onViewCreated() . It sets up a click listener for the random_button , which was originally created as the Next button.

Here is what this code does:

  • Use the findViewById() method with the id of the desired view as an argument, then set a click listener on that view.
  • In the body of the click listener, use an action, which in this case is for navigating to another fragment, and navigate there. (You will learn about that later.)
  • Just below that click listener, add code to set up a click listener for the toast_button that creates and displays a toast. Here is the code:
  • If you want, extract the message string into a resource as you did for the button labels.

You have learned that to make a view interactive you need to set up a click listener for the view that says what to do when the view (button) is clicked on. The click listener can either:

  • Implement a small amount of code directly.
  • Call a method that defines the desired click behavior in the activity.

Step 3: Make the Count button update the number on the screen

The method that shows the toast is very simple; it does not interact with any other views in the layout. In the next step, you add behavior to your layout to find and update other views.

Update the Count button so that when it is pressed, the number on the screen increases by 1.

  • In the fragment_first.xml layout file, notice the id for the TextView :
  • In FirstFragment.kt , add a click listener for the count_button below the other click listeners in onViewCreated() . Because it has a little more work to do, have it call a new method, countMe() .
  • In the FirstFragment class, add the method countMe(), which takes a single View argument. This method is invoked when the Count button is clicked and the click listener called.
  • Use the findViewById() method to get the TextView that shows the count. This method returns a View , so you must cast the result to a TextView . Specify the id of the view to get, textview_first .
  • Get the value of the showCountTextView .
  • Convert the value to a number, and increment it.
  • Display the new value in the TextView by programmatically setting the text property of the TextView .

Here is the whole method:

  • Run your app. Press the Count button and watch the count update.

9. Task: Implement the second fragment

So far, you've focused on the first screen of your app. Next, you will update the Random button to display a random number between 0 and the current count on a second screen.

c7029fe48ec2a802.png

  • How to pass information to a second fragment.

Update the layout for the second fragment

a991c2db96dcafb3.png

Step 1: Add a TextView for the random number

  • Open fragment_second.xml ( app > res > layout > fragment_second.xml ) and switch to Design view if needed. Notice that it has a ConstraintLayout that contains a TextView and a Button .

e49352faab20c765.png

  • Add another TextView from the palette and drop it near the middle of the screen. This TextView will be used to display a random number between 0 and the current count from the first Fragment .
  • Set the id to @+id/textview_random ( textview_random in the Attributes panel.)
  • Constrain the top edge of the new TextView to the bottom of the first TextView , the left edge to the left of the screen, and the right edge to the right of the screen, and the bottom to the top of the Previous button.
  • Set both width and height to wrap_content .
  • Set the textColor to @android:color/white , set the textSize to 72sp , and the textStyle to bold .

81dc7122e9ddaea1.png

  • Set the text to " R ". This text is just a placeholder until the random number is generated.
  • Set the layout_constraintVertical_bias to 0.45 .

This TextView is constrained on all edges, so it's better to use a vertical bias than margins to adjust the vertical position, to help the layout look good on different screen sizes and orientations.

Here is the XML code for the TextView that displays the random number:

Step 2: Update the TextView to display the header

  • In fragment_second.xml , select textview_second , which currently has the text "Hello second fragment. Arg: %1$s" in the hello_second_fragment string resource.
  • If android:text isn't set, set it to the hello_second_fragment string resource.
  • Change the id to textview_header in the Attributes panel.
  • Set the width to match_constraint , but set the height to wrap_content , so the height will change as needed to match the height of the content.
  • Set top, left and right margins to 24dp . Left and right margins may also be referred to as "start" and "end" to support localization for right to left languages.
  • Remove any bottom constraint.
  • Set the text color to @color/colorPrimaryDark and the text size to 24sp .
  • In strings.xml , change hello_second_fragment to " Here is a random number between 0 and %d. "
  • Use Refactor > Rename... to change the name of hello_second_fragment to random_heading .

Here is the XML code for the TextView that displays the heading:

ff7f9969afbd67ff.png

Step 3: Change the background color of the layout

Give your new activity a different background color than the first activity:

  • In colors.xml , add a new color resource:
  • In the layout for the second activity, fragment_second.xml , set the background of the ConstraintLayout to the new color.

In the Attributes panel:

9948b482fb81ef5.png

Your app now has a completed layout for the second fragment. But if you run your app and press the Random button, it may crash. The click handler that Android Studio set up for that button needs some changes. In the next task, you will explore and fix this error.

Step 4: Examine the navigation graph

When you created your project, you chose Basic Activity as the template for the new project. When Android Studio uses the Basic Activity template for a new project, it sets up two fragments, and a navigation graph to connect the two. It also sets up a button to go from the first fragment to the second. This is the button you changed into the Random button. And now you want to send a number when the button is pressed.

  • Open nav_graph.xml ( app > res > navigation > nav_graph.xml ).

A screen similar to the Layout Editor in Design view appears. It shows the two fragments with some arrows between them. You can zoom with + and - buttons in the lower right, as you did with the Layout Editor .

  • You can freely move the elements in the navigation graph. For example, If the fragments appear with SecondFragment to the left, drag FirstFragment to the left of SecondFragment so they appear in the order you work with them.

504c2156d46d4d6b.png

Step 5: Enable SafeArgs

This will enable SafeArgs in Android Studio.

  • Open Gradle Scripts > build.gradle (Module: My First App)
  • Find the dependencies section In the buildscript section, and add the following lines after the other classpath entries:
  • Open Gradle Scripts > build.gradle (Module: app)
  • Just below the other lines that begin with apply plugin add a line to enable SafeArgs:

50cedf1769381459.png

  • Choose Build > Make Project . This should rebuild everything so that Android Studio can find FirstFragmentDirections .

Step 6: Create the argument for the navigation action

  • In the navigation graph, click on FirstFragment , and look at the Attributes panel to the right. (If the panel isn't showing, click on the vertical Attributes label to the right.)
  • In the Actions section, it shows what action will happen for navigation, namely going to SecondFragment .
  • Click on SecondFragment , and look at the Attributes panel.

The Arguments section shows nothing.

  • Click on the + in the Arguments section.

c334d61be24eb01d.png

Step 6: Send the count to the second fragment

The Next / Random button was set up by Android Studio to go from the first fragment to the second, but it doesn't send any information. In this step you'll change it to send a number for the current count. You will get the current count from the text view that displays it, and pass that to the second fragment.

  • Open FirstFragment.kt ( app > java > com.example.myfirstapp > FirstFragment )
  • Find the method onViewCreated() and notice the code that sets up the click listener to go from the first fragment to the second.
  • Replace the code in that click listener with a line to find the count text view, textview_first .
  • Get the text of the view and convert it to an Int .
  • Create an action with currentCount as the argument to actionFirstFragmentToSecondFragment() .
  • Add a line to find the nav controller and navigate with the action you created.

Here is the whole method, including the code you added earlier:

  • Run your app. Click the Count button a few times. Now when you press the Random button, the second screen shows the correct string in the header, but still no count or random number, because you need to write some code to do that.

Step 7: Update SecondFragment to compute and display a random number

You have written the code to send the current count to the second fragment. The next step is to add code to SecondFragment.kt to retrieve and use the current count.

  • In SecondFragment.kt , add an import for navArgs to the list of imported libraries.
  • In SecondFragment.kt , before onViewCreated() , add a line to define where the arguments are.
  • In SecondFragment.kt below where the click listener is created, add lines to get the count argument, get the string and format it with the count, and then set it for textview_header .
  • Add code to get a random number between 0 and the count.
  • Add code to convert that number into a string and set it as the text for textview_random .

Here is the whole method.

Congratulations, you have built your first Android app!

10. Learn more

The intention of this codelab was to get you started building Android apps. We hope you want to know a lot more though, like how do I save data? How do I run background tasks? How do I display a list of photos? How do I ...

We encourage you to keep learning. We have more Android in Kotlin courses built by Google to help you on your learning journey

Written tutorials

  • Android Developer Fundamentals teaches programmers to build Android apps.
  • Kotlin Bootcamp codelabs course is an introduction to Kotlin for programmers. You need experience with an object oriented programming language (Java, C++, Python) to take this course..
  • Find more at developer.android.com , the official Android developer documentation from Google.

Online courses

  • Kotlin Bootcamp for Programmers : This is an introduction to Kotlin for programmers. You need some experience with an object oriented programming language (Java, C++, Python) to take this course.

These interactive, video-based courses were created by Google experts in collaboration with Udacity. Take these courses at your own pace in your own time.

  • Developing Android Apps in Kotlin : If you know how to program, learn how to build Android apps. This course uses Kotlin .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Education, Online Course, LMS Creative

  • Login Login

Kotlin Articles

Kotlin documentation.

Line Shape Image

  • Sofia Martinez
  • Dec 09, 2023

Introduction Kotlin is a modern, statically typed programming language that boosts productivity and increases developer satisfaction. It's officially supported by Google for Android Development and is seamlessly interoperable with Java. The following article aims to explain the comprehensive and extensive Kotlin documentation, which allows developers to learn and further explore the language's features.

  • Getting Started with Kotlin

Table of Contents

  • Understanding Kotlin Syntax

Common Error-Prone Cases and How to Avoid Them

  • Kotlin can be used for various types of development, including server-side, client-side web, and Android. It's fully compatible with Java, meaning you can easily migrate your project or start writing Kotlin code in your existing project.
  • Kotlin code is more concise than Java, which means you can read and write less code with the same functionality. Moreover, Kotlin has null safety built into its system, preventing any null pointer exceptions at compile time.
  • The official Kotlin documentation is a valuable resource for both beginners and experienced programmers. It provides a detailed description of the language syntax, standard library, and Kotlin's use for various tasks. The documentation also includes tutorials, examples, and guides to help you start your journey with Kotlin.
  • The Kotlin documentation is divided into several sections: - Reference: Describes the syntax and basic language structure. - Tutorials: Guides that cover several topics, such as building applications, using the command line, and using Kotlin on Android. - API Reference: Provides detailed information about Kotlin's standard library. - Resources: Contains links to other useful resources, such as GitHub, forums, and the issue tracker.

Understanding Kotlin Syntax Upskill yourself, get started with AI courses 🚀

  • Kotlin's syntax is expressive and concise. It's easy to understand, even for those who are new to the language. Let's look at a simple example: kotlin fun main() { println("Hello, World!") } In this code snippet, `fun` is used to declare a function. `main` is the name of the function, and `println()` is a function that prints a line to the standard output.
  • Variables in Kotlin can be declared using `var` (mutable) or `val` (immutable). Here's an example: kotlin var a = 1 // mutable variable val b = 2 // immutable variable In this example, `a` is a mutable variable, meaning its value can be changed, while `b` is an immutable variable, meaning its value cannot be changed once assigned.
  • One common mistake is trying to access a null reference, which results in a NullPointerException. Kotlin's null safety feature can help avoid this. Here's an example of how Kotlin handles null safety: kotlin var name: String? = null // nullable type name?.let { println(it) } // safe call In this example, `name` is a nullable type, meaning it can hold a null reference. The `?.let` is a safe call, which executes the block of code only if `name` is not null.
  • Another common mistake is using `==` for object comparison. In Kotlin, `==` checks for structural equality, while `===` checks for referential equality. Here's an example: kotlin val a = "Kotlin" val b = StringBuilder("Kotlin").toString() // different instance println(a == b) // prints true, checks structural equality println(a === b) // prints false, checks referential equality In this example, `a` and `b` are structurally equal but not referentially equal. Therefore, `a == b` returns true, and `a === b` returns false.

Ready to kick-start your career?

Shape Image

Kotlin Tutorial

Kotlin classes, kotlin examples, learn kotlin.

Kotlin is a modern, trending programming language.

Kotlin is easy to learn, especially if you already know Java (it is 100% compatible with Java).

Kotlin is used to develop Android apps, server side apps, and much more.

Examples in Each Chapter

Our "Try it Yourself" editor makes it easy to learn Kotlin. You can edit the code and view the result in your browser:

Click on the "Try it Yourself" button to see how it works.

We recommend reading this tutorial, in the sequence listed in the left menu.

Kotlin Exercises

Test yourself with exercises.

Insert the missing part of the code below to output "Hello World".

Start the Exercise

Kotlin Quiz

Learn by taking a quiz! This quiz will give you a signal of how much you know about Kotlin.

Take the Kotlin Quiz

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study at W3Schools without using My Learning.

kotlin how to write documentation

Learn by Examples

Learn by examples! This tutorial supplements all explanations with clarifying examples.

See All Kotlin Examples

Download Kotlin

Download Kotlin from github: https://github.com/JetBrains/kotlin

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

kotlin how to write documentation

How to Simplify Android Documentation with Dokka and KDoc

Pooja Shaji

Pooja Shaji

ProAndroidDev

All good products will include an instruction manual to make it easier for users to use the product. A product that is easy to use can make a big difference. This also applies to writing any software. For developers, understanding code has a huge impact on creating user-friendly applications with correct functionality.

In this blog post, you can see how to use Dokka and KDoc to simplify your Android documentation and make it easier for other developers to work with your code. We will walk through the basics and show you how to use them to create well-organized and easy-to-use Android documentation.

What is code documentation?

Code documentation is the description that helps to understand what each code does in the application. For instance, it helps to give a clear overview of what each variable does, what a particular function is in the project, whether it has a parameter or any return type, and what its impact is in the code like details are being documented well.

Why should we document code?

Imagine you have the opportunity to work on a large project with millions of pieces of code. You are responsible for correcting errors in this section. You find the line of code where the error occurred and the error was caused by the two functions being called, then you navigate to that function code after going through each line of code you discover that an access modifier is causing the problem. As a result, the developer has to go through a lot of code, and they all have to understand the interrelationships between the codes to tackle a problem. Handling an error in a bigger project in this way is clearly a headache for developers, especially for a newbie.

This is where good documentation helps. Code documentation is usually used to understand what variables, classes, objects, functions, etc.. are used in the application and what is its purpose and give information about does it have any parameters, receiver, or does it have external links.

If you get enough info about the code it is easy to work in code which eventually led to a decrease in the amount of time spent on solving and implementing a solution in the application.

But always there are two worst-case scenarios while documenting

Lazy documentation

Lazy documentation is the document with the least information provided. If a document is not giving you enough information about functionalities it is lazily formatted. Which is good for nothing, because it doesn’t bring any value to make you understand the code.

OverInfo Documentation

Some documentation gives information more than what it needs resulting in uncleared usage of code and makes confusion about the code. Spending a fruitful time reading out documentation is important to understand the proper usage of code but what if it takes double effort to understand the code? or information overloading creates too much difficulty in processing the code for a developer or even led to uncleared usage, this happens in over info documentation

Good documentation characteristics

  • Should be understandable
  • It should be accurate and up to date
  • Simple and concise
  • Proper formatting
  • The document should always hit the target
  • Should properly describe each functionality
  • It should properly document its parameters, links, receivers if any

What are KDoc and Dokka?

In Java, Javadoc is used to document java code. Before Dokka, there is no proper tool to document Kotlin. Dokka is a documentation tool that is similar to Javadoc. The main difference between Javadoc and Dokka is that Dokka supports documentation of both Kotlin and Java. Dokka the documentation is made possible with KDoc.

KDoc is the language used to document Kotlin code. To generate good documentation proper commenting is needed, to do this KDoc helps to commend using block tags and markdown. It is basically a plugin used in Android studio which helps to document. We can use KDoc by the following

  • KDoc commenting started using / ** as the opening tag and ended using the */ closing tag
  • KDoc supports block tags and inline and HTML markdown to provide additional information about the elements which is embedded using @ symbol
  • @receiver: document receiver extension
  • @param: documents properties of class or functions with name and description
  • @see: documents link to a specified class or function

Inline Markdown

  • # h1, ## h2, [], > etc.. tags are supported

<i>, <img>, <html>, <head> etc.. tags can also be used

Read more about markdown guides to get familiar

It is a tool used in to generate documentation. The generated documentation can be viewed basically in formats that include HTML, markup, and standard Javadoc . Dokka supports documentation of both java and Kotlin. It generates a Kotlin document if it is embedded using KDoc in the Kotlin file and generates Javadoc if commented using Javadoc comments.

How to implement

1. implement dependencies in project-level build.gradle, 2. implement dependencies in module-level build.gradle.

  • If you have multiple modules add in there too
  • Sync project

After a successful build do the following steps

3. Document Generation

Open the terminal option in Android Studio and type the following

  • To generate a document for the module type the script in terminal
  • To generate a document for multi-module type as follows

Once it completes the process you can see the generated document in build/dokka by changing the view type from Android to Project. Here is a sample dokka build generated in open source project Sliderz .

And by clicking the index.html and opening the browser we can see the code documentation generate in HTML format which is the default format.

The Dokka also supports other formats including Javadoc, gfm, and Jekyll.

But if we have not included any Kdoc commenting then it will give a blank HTML document. To do so we have to include KDoc comment. The normal commenting using // comment, /* comment*/, <!-comment → are not regarded as Kdoc comments. We can do Kdoc commenting using the below symbol.

Kdoc Commenting

  • More explanatory code documentation only happens by choosing suitable naming conventional and clearly defined variable names.
  • You can provide additional details to be displayed in the documentation

Sample Kdoc commenting example

/** * Performs a complicated operation. * * @param remote If true, executes operation remotely * @return The result of executing the operation * */ fun foo(remote: Boolean): Result { … }

It can be further expanded if it has a constructor, exception throwing, etc.. are implemented in code.

You can look at the further Block Tags used in the official KDoc documentation.

https://kotlinlang.org/docs/kotlin-doc.html#module-and-package-documentation

This is a quick guide for implementing Dokka in the android studio. You can check the further syntax in the above link.

This whole blog is about basic information about documentation. Hope you enjoyed it and helpful in your development journey. That’s all for today.

Have a nice day 👋👋👋👋

Pooja Shaji

Written by Pooja Shaji

📱Android dev & 🧾tech blogger. Passionate about open source & software development. Check out my works on GitHub https://github.com/kodeflap ✨✨✨

More from Pooja Shaji and ProAndroidDev

Choosing Android Architectures: MVC, MVP, MVVM, Clean Architecture, and MVI

Choosing Android Architectures: MVC, MVP, MVVM, Clean Architecture, and MVI

When developing android applications, choosing the right architecture is crucial for building maintainable, scalable, and testable code….

An org chart

Coroutine patterns in Android, and why they work

I know many android developers who learn coroutines through code patterns, and that is usually enough to get by. but doing so misses the….

Debug Android API Calls Like a Boss

Debug Android API Calls Like a Boss

Flipper, chucker, android studio, or adb which is the best tool to inspect api calls.

Different ways to handle Android Gradle dependencies

Different ways to handle Android Gradle dependencies

As an android developer, you use gradle for adding dependencies, configurations, tasks, etc. related to your project. it is simple to…, recommended from medium.

Create .aar file in android

Hassan Mirza

Create .aar file in android

This article guides that how to create .aar files in android project..

JSON is incredibly slow: Here’s What’s Faster!

Vaishnav Manoj

DataX Journal

JSON is incredibly slow: Here’s What’s Faster!

Unlocking the need for speed: optimizing json performance for lightning-fast apps and finding alternatives to it.

kotlin how to write documentation

General Coding Knowledge

kotlin how to write documentation

Medium's Huge List of Publications Accepting Submissions

What’s new in Flutter 3.16

Kevin Chisholm

What’s new in Flutter 3.16

Material 3 by default, impeller preview for android, devtools extensions, and much more.

How I Setup My MacBook for Development (2024 Version)

Crizant Lai

How I Setup My MacBook for Development (2024 Version)

Unlocking the potential of the cutting-edge macbook setup in 2024..

I Built an App in 6 Hours that Makes $1,500/Mo

Artturi Jalli

I Built an App in 6 Hours that Makes $1,500/Mo

Copy my strategy.

Jacob Bennett

Jacob Bennett

Level Up Coding

The 5 paid subscriptions I actually use in 2024 as a software engineer

Tools i use that are cheaper than netflix.

Text to speech

  • Skip to main content
  • Skip to search
  • Sign up for free

kotlin how to write documentation

Creating effective technical documentation

Author avatar

Effective feature documentation is important in enhancing a user's experience with the feature. Good documentation is like a piece of the puzzle that makes everything click — the key for encouraging feature adoption.

To support you in creating effective technical documentation, this article provides an overview of the core principles of technical writing. It also highlights the best practices for creating clear and accessible documentation. Applying these technical writing principles helps us maintain the high quality of content on MDN. Whether you're documenting your own project or product or contributing to technical content in various settings, you can improve the quality of your work by following these best practices.

Adopt clarity, conciseness, and consistency

These three Cs form the core principles of technical writing. They can take you a long way in producing quality documentation.

For achieving clarity in your writing, apply the following guidelines:

  • Use simple words and clear language. Keep in mind the audience, especially if it includes non-native English speakers.
  • Be clear about who needs to perform the action. Writing in active voice is not strictly required. However, you should use it when you want to be clear about who needs to perform the action. For example, clarify whether a function is triggered by an event or if the user needs to explicitly call the function.
  • Clearly introduce and explain new terms. This helps to lay the foundation for concepts that are covered later in the documentation.
Tip : Replace "it", "this", and "these" with proper nouns if they can refer to more than one thing in the given context.
  • Aim for one idea per sentence to improve readability.
  • Stick to one main idea per paragraph. Each sentence in a paragraph should logically connect to the one before it. Imagine if each sentence in a paragraph was a link in a chain. If you pick up the first link, the other links in the chain should follow, forming a continuous sequence. This is how the sentences should connect to each other, ensuring a seamless flow of a single idea.

Conciseness

Keep sentences short. This automatically increases the readability and clarity of your document. It also helps in quick comprehension. Long sentences can be more challenging to understand quickly due to their complex structures.

Tip : Based on common readability standards, aim for 15-20 words per sentence.

For additional insights on sentence length and readability strategies, see Simple sentences (on https://readabilityguidelines.co.uk ) and Popular readability formulas , including the Flesch-Kincaid index, on Wikipedia.

Consistency

Use the same terminology throughout your documentation to ensure a seamless reader experience. For example, if you start referring to "user agents" as browsers, stick with that term consistently. This avoids confusion that can arise from using words interchangeably, even when they share the same meaning.

Additionally, maintain consistent word casing and follow a uniform formatting style throughout your documentation. These practices not only enhance readability but also contribute to a professional presentation of your documentation.

Organize your content for maximum impact

Apply the same principles for organizing your content as you would for organizing your code: spend some time setting a clear goal and thinking about the desired structure for your documentation. Ensure that each subsection contributes to this goal incrementally.

Start with an introduction

In the introduction, first describe the feature you're documenting. Next, set the context by explaining why learning about the feature would be beneficial to the readers. This can include describing real-life scenarios where the feature can be useful. The more relevance you add to the topic, the easier it will be for readers to understand and engage with the content.

Progress logically

The following questions can help you ensure that your content is progressing logically:

  • Is your document structured to guide readers from foundational concepts to more advanced ones? Are there sections to introduce the " what " to establish a base before delving into the " why " and " how "? Consider whether the document structure mirrors the natural learning path for the topic. Aligning the document's structure with the natural progression of learning helps readers build their knowledge step-by-step and also enhances the overall learning experience.
  • Are there sufficient how-to guides or examples following the conceptual sections?
  • Consider the flow of the content. Is it following a logical sequence — from one sentence to the next, from one paragraph to the next, and from one section to the next? Does each section logically build on the information presented previously, avoiding abrupt jumps or gaps in the content?

Additionally, as you work on the draft, always ask yourself:

  • What reader questions am I addressing with this sentence?
  • Can I add a simplistic or real-life use case to explain this concept?

Include examples

Imagine sitting next to someone as you explain the concepts to them. Preempt their questions and address them in your writing. Use this approach to add as many relevant examples as possible.

When adding examples, don't restrict yourself to only code; include non-code scenarios to demonstrate a feature's utility. This helps readers understand the concepts better and also caters to different learning styles. Consider providing real-world scenarios or use cases to illustrate how the feature or concept applies in practical situations.

Optimize the document structure and length

Evaluate your documentation's structure to ensure it maintains a logical and balanced hierarchy.

  • Ensure that each section and subsection has a clear purpose and sufficient content.
  • Look for instances where a main section contains only one subsection (orphan), such as a single H3 section under an H2 section. This indicates that you need to reorganize your content or make some additions.
  • Check if there are lower-level headings such as H4 . Too many subsections can be overwhelming for readers, making it difficult for them to grasp the information. In such cases, consider presenting the content as a bulleted list instead to help readers retain the key points more effectively. This approach helps to simplify the hierarchy and also contributes to easier navigation.
  • While there should be sufficient content for each section, pay attention to the overall length. If any section becomes too extensive, it can be overwhelming for readers. Split large sections into multiple logical subsections or restructure the content into new sections and subsections. Grouping content into digestible pieces helps maintain focus and improve navigation for readers.

Proofread your writing

One aspect that cannot be stressed enough is the importance of self-reviewing and proofreading what you've written. Whether you're creating a large document or a short paragraph, this step is crucial.

Taking the time to fully review your work will help you identify sections that don't flow well or can be improved for clarity. During self-review, aim to spot and remove redundancy (repetition of ideas without adding value) and repetitiveness (overuse of words or phrases). These refinements will ensure your documentation is clear and coherent and conveys your ideas as intended.

Proofread and then take a break before you review again. Only then submit your work. While spell checkers can flag spelling errors, they might not flag incorrect use of words, such as an unintended use of "he" instead of "the". It's best to take a break and return with fresh eyes to catch any errors you might have missed. Pay close attention to identify inconsistencies in tone, style, tense, or formatting and make the necessary adjustments.

Additional tips

To improve the clarity and accessibility of your documentation, also keep the following guidelines and tips in mind. To go in-depth into any of the topics, feel free to consult our Writing style guide .

  • Bulleted vs numbered lists : Lists, in general, make documentation easier to scan. Use bulleted lists when there is no specific order of the items. Use numbered lists when the steps need to be followed in the specific order. Always include a lead-sentence before beginning a list to provide context.
  • Commas : Use a comma after an introductory clause to improve readability and to clarify the sentence structure. Use a comma to separate items in a list to ensure clarity.
  • Alt text : Always provide an alternative text for the images you add to content. This makes your documentation accessible to people using screen readers. In addition to images, ensure that video and audio files have accompanying descriptive texts.
  • Descriptive link text : Make sure each link text is clear even out of context and clearly indicates where the link leads. Descriptive link texts also help people using screen readers understand the destination of links. For example, use "Read our writing style guide to learn more" instead of "Click here to learn more".
  • Inclusive language : Make your documentation welcoming to everyone. Strive to use words that respect and acknowledge the diversity of your audience.

That's it for this article. I hope you found these tips helpful as a quick refresher on technical writing best practices. Remember that learning how to create effective and easy-to-use documentation is an ongoing process. It starts with understanding your audience and the goals of your documentation. By applying these technical writing principles and tips, you'll certainly be able to enhance the clarity and overall quality of your documentation.

Let me know if you learned something new or if there's any idea that resonated with you. I'd also like to hear if there are any best practices you use in your technical documentation workflow. Share with us on Mastodon or Discord .

Previous Post Leveraging Bun on Vultr: A superior Node.js alternative

Stay informed with mdn.

Get the MDN newsletter and never miss an update on the latest web development trends, tips, and best practices.

  • Blogs by Topic

The JetBrains Academy Blog

The place for learning and teaching computer science your way

  • Twitter Twitter
  • Facebook Facebook

Learn IDE Code Refactoring in Kotlin for Enhanced Code Quality

Clara Maine

Do you know what your code smells like?

If you aren’t sure, you would probably benefit from learning how to assess code smell with our new course, Introduction to IDE Code Refactoring in Kotlin . The course teaches you how to use your IDE to format and reshape your code to become more readable and less likely to break. It’s an excellent choice for beginner to intermediate programmers looking to write professional code.

kotlin how to write documentation

Content overview

The course consists of eight sections where you can learn and apply different refactoring techniques. You’ll learn best practices for code style and formatting, how to identify and avoid common issues, and how to use your IDE more efficiently to enhance the quality of your code.

Some more topics you can look forward to learning about in the course:

  • Naming conventions and style rules
  • Root canal vs. floss refactoring
  • Automatic refactoring techniques for moving, extracting, and inlining code
  • Refactoring to design patterns

kotlin how to write documentation

IDE learning

Many programming courses are IDE-agnostic, but if you want to learn effective refactoring techniques, this makes it difficult to showcase essential features and shortcuts specific to your IDE. With the JetBrains Academy plugin , your course is integrated into the same window as your IDE, making it easier to immediately apply the theory you learn.

Learn in Kotlin

The course uses the Kotlin Language, but if you don’t know it yet, don’t worry! The course is a great way to get introduced, and if you want a more comprehensive introduction to the language, you can check out our Kotlin Onboarding courses . A Java-specific version is also in the works and will be released soon.

For the added benefits of social learning, consider joining our dedicated Discord server! There, you can find accountability partners and get support from members of the JetBrains Academy team.

Free on JetBrains Marketplace

Access Introduction to IDE Code Refactoring in Kotlin today by following these steps:

  • Download either IntelliJ IDEA Community Edition (completely free) or IntelliJ IDEA Ultimate (available with a 30-day free trial).
  • Go to the Learn tab on the Welcome screen.
  • Enable access under Learn to Program .

From there you’ll be able to find the course by locating it in the list of Marketplace courses.

If you have any questions or would like to share your feedback, feel free to leave a comment below or contact us at [email protected] .

Happy learning!

Your JetBrains Academy team

Meet the course authors

kotlin how to write documentation

Zarina Kurbatova is a software developer at JetBrains Machine Learning Methods in the Software Engineering Lab. She has been conducting research in the refactoring field, developing tools, writing academic papers, and presenting results at software engineering conferences.

kotlin how to write documentation

Anna Potriasaeva is a software developer at JetBrains Machine Learning Methods in the Software Engineering Lab. She specializes in developing tools for refactoring and education.

Subscribe to Blog updates

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

kotlin how to write documentation

Help Us Shape the Future of Computer Science Education

Take the Computer Science Learning Curve survey, share your insights, and get a chance to win a 13" M2 MacBook Air!

Julia Amatuni

JetBrains Academy: New Learning Content in February

Check out the new interactive projects to improve your skills in JavaScript, Go, and C++.

Regina Muradova

JetBrains Academy: Looking Back at 2023

Explore the achievements that made us the most proud in 2023!

kotlin how to write documentation

JetBrains Academy January Digest

Embrace a fresh start in 2024! Transform computer science education with the JetBrains Academy survey, explore new courses or create your own, and join IT events for insights and networking opportunities.

Maria Sharobaeva

IMAGES

  1. How to Document a Kotlin Project

    kotlin how to write documentation

  2. How to add documents to your Kotlin API using KDoc and Dokka?

    kotlin how to write documentation

  3. How to Document a Kotlin Project

    kotlin how to write documentation

  4. Revamped Kotlin Documentation

    kotlin how to write documentation

  5. Introduction to Kotlin Documentation with Dokka

    kotlin how to write documentation

  6. Variables and Data Type in Kotlin

    kotlin how to write documentation

VIDEO

  1. 057 Kotlin docs

  2. When you have only 5 minutes to write documentation

  3. 008 list in kotlin

  4. 071 Mastering kotlin collections

  5. 19 Getters/ Setters (Kotlin course)

  6. Mastering Documentation in Xcode: A Comprehensive Guide #XcodeDocumentation #DeveloperTools

COMMENTS

  1. Document Kotlin code: KDoc

    The language used to document Kotlin code (the equivalent of Java's Javadoc) is called KDoc. In essence, KDoc combines Javadoc's syntax for block tags (extended to support Kotlin's specific constructs) and Markdown for inline markup. Kotlin's documentation engine: Dokka, understands KDoc and can be used to generate documentation in various formats.

  2. An Introduction to KDoc

    KDoc is the official format for documenting Kotlin code. It's an extension to Javadoc that supports Kotlin's specific constructs. In this tutorial, we'll explore the fundamentals of KDoc, its benefits, and how to use it effectively. We'll also look at some of the different ways to use KDoc to document Kotlin code. 2. Understanding KDoc

  3. Get started with Kotlin

    Create your first backend application: To start from scratch, create a basic JVM application with the IntelliJ IDEA project wizard. If you prefer more robust examples, choose one of the frameworks below and create a project: Use Kotlin and third-party libraries in your application.

  4. Introduction to Kotlin Documentation with Dokka

    Overview In this quick tutorial, we'll look at handling documentation with Dokka. Dokka is a documentation engine for Kotlin that generates API documentation in various formats, including HTML, PDF, and Markdown. In the first part of the article, we'll see how to include Dokka in our Gradle or Kotlin project.

  5. Kotlin and Android

    Kotlin is open source. Kotlin is an open source project available at no charge under the Apache 2.0 license. The code for the project is developed openly on GitHub primarily by the team employed at JetBrains, with contributions from Google and others. Our choice of Kotlin reaffirms our commitment to an open developer ecosystem as we evolve and ...

  6. Appendix B. Documenting Kotlin code · Kotlin in Action

    The format used to write documentation comments for Kotlin declarations is similar to Java's Javadoc and is called KDoc. Just as in Javadoc, KDoc comments begin with /** and use tags starting with @ to document specific parts of a declaration.

  7. Functions

    Kotlin functions are declared using the fun keyword: fun double(x: Int): Int { return 2 * x } Function usage Functions are called using the standard approach: val result = double(2) Calling member functions uses dot notation: Stream().read() // create instance of class Stream and call read () Parameters

  8. Kotlin documentation (KDoc) guidelines

    Guidelines for writing KDoc. Every parameter / property in a function / class should be documented. Consider using all available tags to add documentation for elements. Use for each API that represents a standalone feature, or advanced behavior for a feature. Do not link to the same identifier inside documentation.

  9. Basic syntax

    Basic syntax Edit page Last modified: 15 January 2024 This is a collection of basic syntax elements with examples. At the end of every section, you'll find a link to a detailed description of the related topic. You can also learn all the Kotlin essentials with the free Kotlin Core track by JetBrains Academy. Package definition and imports

  10. Documentation with KDoc for Kotlin/Android

    Here is KDoc, a language for writing documents for Kotlin code !!! Similar to JavaDoc you the main format for KDoc is : starting with /** and end with */. In KDoc we can use tags, a tag formula is ...

  11. Documenting Kotlin Code for Android Using KDoc and Dokka

    Home ... Documenting Kotlin Code for Android Using KDoc and Dokka Documenting Kotlin Code for Android Using KDoc and Dokka Mar 28 2022 , Kotlin 1.5, Android 4.4, Android Studio 2020.3.1 Learn how to use KDoc to document your Kotlin code and generate beautiful-looking documentation pages using Dokka. By Rajdeep Singh . 5 (2) · 1 Review

  12. Harnessing the Power of the Kotlin DSL for Documentation

    The essence of the Kotlin DSL. The Kotlin DSL for documentation is a framework specifically designed for creating documentation and static websites. The framework is a type-safe builder operating on basic document elements, while additional functionality plugs in as user code or external dependencies. The dependencies can deliver any kind of ...

  13. Kotlin: which format to use for documentation?

    4. The just published M11 release of Kotlin officially supports a new documentation format based on a combination of Markdown and JavaDoc. You can find the full documentation for it here. The new documentation generation tool will be officially released in a very short while. Right now it's available in a Git repository here.

  14. How to add documents to your Kotlin API using KDoc and Dokka?

    Writing documents for your API users is a must-have.In this video, you will learn how to add documents to your Kotlin API using KDoc and how to export them u...

  15. Document Your Android With Dokka and KDoc

    To write documentation for Kotlin code we can use the following plugin: KDoc-er - Kotlin Doc Generator - IntelliJ IDEs Plugin | Marketplace. KDoc-er Introducing A simple and lightweight KDoc generator. KDoc is a language used to document the Kotlin codes. plugins.jetbrains.com. With the plugin, we can automatically generate Kdocs like this: ...

  16. Build Your First Android App in Kotlin

    1. Welcome! In this codelab, you'll learn how to build and run your first Android app in the Kotlin programming language. (If you're looking for the Java version of this codelab, you can go here.) Kotlin is a statically typed programming language that runs on the JVM and is completely interoperable with the Java programming language. . Kotlin is an officially supported language for developing ...

  17. Comprehensive Guide to Kotlin Documentation

    Kotlin code is more concise than Java, which means you can read and write less code with the same functionality. Moreover, Kotlin has null safety built into its system, preventing any null pointer exceptions at compile time. Kotlin Documentation; The official Kotlin documentation is a valuable resource for both beginners and experienced ...

  18. Introduction

    Complete and easy-to-understand documentation Minimum cognitive complexity Consistent API This guide contains a summary of best practices and ideas to consider when writing an API for your library. It consists of the following chapters: Readability Predictability Debuggability Backward compatibility

  19. Kotlin Tutorial

    Learn Kotlin. Kotlin is a modern, trending programming language. Kotlin is easy to learn, especially if you already know Java (it is 100% compatible with Java). Kotlin is used to develop Android apps, server side apps, and much more. Start learning Kotlin now ».

  20. How to Simplify Android Documentation with Dokka and KDoc

    Dokka is a documentation tool that is similar to Javadoc. The main difference between Javadoc and Dokka is that Dokka supports documentation of both Kotlin and Java. Dokka the documentation is made possible with KDoc. KDoc. KDoc is the language used to document Kotlin code. To generate good documentation proper commenting is needed, to do this ...

  21. Kotlin Docs

    Kotlin overview. What's new in Kotlin. Releases and roadmap. Basics. Concepts. Multiplatform development. Platforms. Standard library. Official libraries. API reference. Language reference. Tools. Compiler and plugins. Learning materials. Early access preview (EAP) Other resources. Uh Oh! Something went wrong.

  22. How to write annotation for documentation in Kotlin?

    How to write annotation for documentation in Kotlin? Ask Question Asked 3 years ago Modified 3 years ago Viewed 99 times 0 I would like to add documentation in source code not attached to any specific Kotlin class or method, it's like conceptual, high-level documentation.

  23. Creating effective technical documentation

    Good documentation is like a piece of the puzzle that makes everything click — the key for encouraging feature adoption. To support you in creating effective technical documentation, this article provides an overview of the core principles of technical writing. It also highlights the best practices for creating clear and accessible documentation.

  24. How to document attributes in Kotlin data class?

    1 Answer. As described in the documentation, you can use the @property tag for this: /** * Represents a person. * @property firstName The first name. * @property lastName The last name. */ data class Person (val firstName: String, val lastName: String) Alternatively, simply mention the property names in the description of the class, if you don ...

  25. Learn IDE Code Refactoring in Kotlin for Enhanced Code Quality

    Learn in Kotlin. The course uses the Kotlin Language, but if you don't know it yet, don't worry! The course is a great way to get introduced, and if you want a more comprehensive introduction to the language, you can check out our Kotlin Onboarding courses. A Java-specific version is also in the works and will be released soon. Community