Kotlin Tutorial 8 — Modularity
This tutorial will cover how to create a library and use one developed by someone else. Concepts like packages and organising code in a project will also be looked at. Every kt file can be put into a package to group related functionality. With Atom create a new project directory called kotlin_tutorial8. In the project directory create the src/org/acme directory. Create the src/org/acme/test.kt file with the following contents and run it:
You may have noticed with the previous tutorial that none of the kt files needed to have the package line since it is optional. As you can see in the code sample above any kt file that is in a package must be in the package directory and the package line must be at the top of the file. If you are creating a Kotlin library then there doesn’t need to be a main function present in any of the kt files before compiling it with the Kotlin compiler (kotlinc).
Using The Kotlin Tools
Now onto a more elaborate example using the same project directory and two Kotlin command line programs: kotlinc, and kotlin (runs Kotlin programs). Create the src/org/acme/greeting.kt file with the following contents:
Replace the contents of src/org/acme/test.kt with the following:
Do the following to create and run the program:
- Open a terminal
- Change directory to your project directory
- Compile the program by running the following: kotlinc src -include-runtime -d test.jar
- Run the program by running the following: kotlin test.jar
Since greeting.kt is in the same package there is no need to import the greeting function. As you can see it is straightforward to compile and run a Kotlin program.
Importing
Just like Python Kotlin uses the import keyword to import items like functions, constants, variables, and even top level items into a source file so they can be used. In your project directory create the src/org/acme/random directory. Create the src/org/acme/random/misc.kt file with the following contents:
In src/org/acme/test.kt replace its contents with the following:
Note that you can import everything from a package with the * character like this: import org.acme.random.*.
Conclusion
You now have an understanding of how to create libraries and use ones developed by other people. Were now at the point in the tutorial series where the next lot of tutorials after Kotlin Tutorial 9 go into OOP (Object Orientated Programming). Next tutorial provides a basic guide on using an IDE in Kotlin Tutorial 9 — Using An IDE.
TOC
- Kotlin Tutorial 1 — Introduction
- Kotlin Tutorial 2 — Basic Data Types
- Kotlin Tutorial 3 — Basic Operators
- Kotlin Tutorial 4 — Handling Input And Output
- Kotlin Tutorial 5 — Basic Collections
- Kotlin Tutorial 6 — Control Flow
- Kotlin Tutorial 7 — Functions
- Kotlin Tutorial 8 — Modularity
- Kotlin Tutorial 9 — Using An IDE
- Kotlin Tutorial 10 — Classes
- Kotlin Tutorial 11 — Inheritance
- Kotlin Tutorial 12 — Encapsulation And Polymorphism
- Kotlin Tutorial 13 — Generics