Kotlin For Python PDF
Kotlin For Python PDF
Kotlin For Python PDF
Documentation
Release 1.0.0
2 Setup 5
2.1 The Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 The IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 The Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.4 Project Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
3 Hello World 7
3.1 The REPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 First File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 Braces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4 Quotation Marks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.5 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.6 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.7 String Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.8 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.9 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.10 Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.11 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5 Conditionals 19
7 Functions 23
8 Classes 25
i
ii
Kotlin for Python Developers Documentation, Release 1.0.0
Kotlin: it’s new, it’s hot, it’s exciting! If you’re a Python developer, you might be interested in Kotlin for Android
development. If you’re a PyCharm user, you might want to write an IDE plugin, using Kotlin.
In both cases, you’re looking to to add Kotlin to your programming arsenal. This documentation teaches Kotlin – from
the perspective of a Python developer who knows nothing about Kotlin, Java, Gradle, or the JVM.
Contents 1
Kotlin for Python Developers Documentation, Release 1.0.0
2 Contents
CHAPTER 1
In no time at all, Kotlin has become an important language to learn, with videos and tutorials and examples
and. . . everything you could want.
Unless you’re a Python dev. Kotlin is “better Java”, but most resources presume you know Java and its ecosystem. It
sure would be nice if this shiny new toy was explained in Python terms.
That’s what we’re doing in this guide. Assuming you know nothing about Java, Gradle, etc., we’re going to get you
productive in Kotlin and IntelliJ. If you’re not a Python developer, you will likely still find this guide useful.
1.2 Contributing
We want this guide to be community-oriented and collaborative. Did we do something stupid? File a ticket or even
send us a pull request.
3
Kotlin for Python Developers Documentation, Release 1.0.0
Setup
Before jumping into features of the language, let’s get ourselves setup. Both Kotlin and Python have sites that let you
enter and evaluate code in a browser. For our purposes, let’s compare getting a real, local setup for each language.
Getting Python and Java installed are similar exercise, but with different obstacles. For Python, while two of the major
platforms ship a Python, everybody on earth will beat you over the head if you use “the system Python”. For Java, it
is not installed by default on most platforms.
Thus, both Python and Java mean an initial, joyful step into the “How do I install it?” thicket.
This is covered in depth elsewhere, so we’ll skip it. From a Pythonista’s perspective, it’s pretty similar. You have to
make some choices about which Java distribution, but we have some dirty laundry here as well – 2 vs. 3, python.org
vs. platform-y Homebrew etc. vs. Anaconda, PyPy vs. Jython vs. weird experiment of the week.
Call this one a tie.
We’re JetBrains: we’re going to use the IDE as the entry point for making a project. For both Python and Kotlin, you
might make your new project environment from the command line and then open it.
Let’s use the IDE make our project, following along with the very-useful Getting Started with IntelliJ IDEA documen-
tation.
In PyCharm, you fire it up and have 3 choices: create a new project from scratch, open a directory on disk, or get a
clone from a VCS system. In the first, you can choose from some project templates, but you then have the important
5
Kotlin for Python Developers Documentation, Release 1.0.0
In Python, that’s about it. You could, at this point, just make a .py file and nobody would complain. Maybe a
.gitignore.
You could, of course, be a grown-up and make a Python package. You’d then be teleported into a world of confusion:
setup.py vs. requirements.txt (vs. Pipfile vs. buildout.cfg), MANIFEST.in, setup.cfg, do I
put my sources under project_name or src/project_name. But those are university politics, not state-ordered
mandates.
Talk about: src/main/kotlin/someFile.kt and whether that path matters, vs. com.pauleveritt.projectname and how that
affects choices.
6 Chapter 2. Setup
CHAPTER 3
Hello World
Java is installed, our IDE has a project open, we’re ready to write some code. In this step we breeze through a light
treatment of many Kotlin concepts, all from the Python perspective.
Python has an interactive interpreter, aka REPL, which makes it easy to play around and learn. It’s a dynamic language,
so this makes sense. As it turns out, Kotlin (in IntelliJ) has a REPL also.
Opening the Kotlin REPL is easy. You can use the Tools | Kotlin menu or search for the action:
7
Kotlin for Python Developers Documentation, Release 1.0.0
In Python we have the Python Console tool window, which opens the Python interpreter in the context of your
project. The Kotlin REPL is the same idea.
Let’s type in some code:
Here we typed a line of Kotlin code and executed it with Cmd-Enter (macOS.) We could have clicked the green
play button, which triggers the run action just like Cmd-Enter. Kotlin evaluated our line, letting Kotlin/Java do a
mountain of machinery behind the scenes.
The REPL can handle multiple lines:
As this is our first foray into Kotlin, let’s analyze this small bit of code from the Python perspective:
• We declare variables with var (which allows re-assignment) or val (which is like a constant). Python doesn’t
have var.
• Double quotes for strings
• No semicolons!
• A print function (like Python 3, but unlike Python 2)
All in all. . . other than var, it’s exactly like Python.
Click the red X to close the REPL and let’s start writing some Kotlin code.
In Python, we’d make a .py file and start typing in some code. From Python’s semantics, there are almost no rules
about the file itself – name, location, etc. For example, here is a minimum hello_world.py:
1 # Python
2 print("Hello World")
We can start the same in Kotlin. IntelliJ has created a src directory for you. Right-click on that and create a file at
src/hello_world/hello_world.kt:
1 # Python
2 def main():
3 print("Hello World")
4
6 main()
Python uses def to define a function, Kotlin uses fun. We’ll talk more about this in Functions.
The Kotlin file shows the standard Kotlin “entry point”: by convention, the file being executed must have a function
named main which accepts a single argument, an array of strings. Kotlin itself then calls this main function. This is a
bit similar to the common (but not required) Python run block. For example, this file in Python might look like this:
1 # Python
2 def main():
3 print("Hello World")
4
6 if __name__ == '__main__':
7 main()
In this Python example, we had to both detect that the module was being run (instead of imported) and then call the
appropriate “main” function.
We saw strong typing in the Kotlin function definition. Python of course has typing, but it is at run time and is inferred.
(We’ll discuss type hinting in the section on Variables and Types.)
Time to run this, which really means, compile and execute. If you’re familiar with PyCharm run configurations and
gutter icons, it’s similar. Click the Kotlin symbol in the gutter for line 1 and select Run:
[TODO screenshot of running it]
Note: IntelliJ prompted us to Run 'Hello_worldKT'. What’s Hello_worldKT? Answer: To make Java
happy, Kotlin generated a Java class behind the scenes.
When you clicked this, there was a lag that you don’t get in Python. This the build/compile phases from Java. It’s
incremental, so it is faster after the first time.
Now that we’ve run our program, let’s breeze through some head-to-head comparisons on a few programming language
basics.
3.3 Braces
This is the most obvious point: like most other programming languages, Kotlin delimits blocks with braces. Python
uses indentation.
3.3. Braces 11
Kotlin for Python Developers Documentation, Release 1.0.0
Switching between languages, or even projects, means swinging back and forth between single versus double quotes
for strings. For example, TypeScript prefers double quotes, but ReactJS ES6 applications prefer single quotes. And
they are both (sort of) JavaScript!
Python’s PEP 8 style guide doesn’t prefer one or the other, but most Python projects seem to use single quotes. In
fact, Python has triple quoted strings!
1 # Python
2 hello = 'world' # best
3 hello = "world" # ok
4 hello = """
5 world""" # triple
Java (and Kotlin) use a single quote for a single character value and double quotes for strings. Triple-quotes indicates
a raw string:
1 // Kotlin
2 val c = 'C' // character
3 val hello = "hello" // string
4 val raw_string = """
5 line 1
6 line 2
7 """
3.5 Comments
Kotlin supports the two familiar styles of comments: end-of-line and block comments:
IntelliJ (and thus PyCharm) as an IDE makes it easy to comment and uncomment lines and selections with Cmd-/.
Python, of course, only uses hash # as the comment symbol, with no block comments:
1 #
2 # Python multiline commments
3 # have a lot of hashes.
4
3.6 Variables
Python doesn’t have any special syntax for declaring a variable. You just assign something:
1 # Python
2 hello = 'world'
Kotlin, though, does. In fact Kotlin has two keywords: one to declare a read-only immutable value, and one for a
mutable variable:
1 // Kotlin
2 val hello = "world" // Read-only, val == value
3 var hello = "world" // Can be re-assigned, var == variable
Where’s the Java-style type noise? Good news – Kotlin can infer the type. The above is the same as being explicit:
1 // Kotlin
2 val hello: String = "hello"
Also, like Python, you can initialize a variable without assigning it:
1 // Kotlin
2 var hello
Of course with Python 3.6 variable annotations, we can make Python look much more like Kotlin. We cover this in
the section on Variables and Types.
Python – the “there should be one way to do things” language – actually has several ways to do string templates:
1 # Python
2 msg = 'World'
3 print('Hello %s' % msg) # Original
4 print('Hello {msg}'.format(msg=msg)) # Python 3 (then 2)
5 print(f'Hello {msg}') # Python 3.6
6 print(f'Hello {msg.upper()}') # Expressions
1 // Kotlin
2 msg = "World"
3 print("Hello $msg")
4 print("Hello ${msg.toUpperCase()}")
3.8 Functions
1 # Python
2 def four():
3 return 2 + 2
1 // Kotlin
2 fun four(): Int {
3 return 2 + 2
4 }
Kotlin adds the curly braces and has to define the return type (which can be omitted if there is no return value.)
But watch this – a function expression:
1 // Kotlin
2 fun four() = 2 + 2
Admit it, that’s pretty sexy. Function expressions are a big new idea which we’ll cover in the section on Functions.
Passing in function arguments is straightforward in Python:
1 # Python
2 def combine(x, y):
3 return x + y
1 // Kotlin
2 fun sum(a: Int, b: Int): Int {
3 return a + b
4 }
You have to provide the type information on the function arguments and return value.
3.9 Conditionals
Let’s take a quick look at things like conditionals and looping. In Python, an if/then/else is straightforward,
with use of indentation:
1 # Python
2 if a > b:
3 return a
4 else:
5 return b
Kotlin looks quite similar, adding parenthesis (optional in Python) and braces:
1 // Kotlin
2 if (a > b) {
3 return a
4 } else {
5 return b
6 }
3.10 Looping
1 # Python
2 items = ('apple', 'banana', 'kiwi')
3 for item in items:
4 print(item)
Here we’ve created an immutable sequence (a tuple) in items. We looped over it in the most basic way possible.
In Kotlin, we have a different construct for making the sequence. Looping is similar, though we use a parentheses
after for:
1 // Kotlin
2 val items = listOf("apple", "banana", "kiwi")
3 for (item in items) {
4 println(item)
5 }
In this case we used println. In Python, the print function always makes a newline unless you ask it not to.
Both Python and Kotlin have rich and interesting control structures, giving both power and terseness. We’ll see more
in Sequences and Looping.
3.11 Classes
Lots to cover later on this, so for now, let’s just view the simplest couple of cases. The minimum in Python:
1 # Python
2 class Message:
3 pass
In Kotlin:
1 // Kotlin
2 class Message
It’s hard to tell which of those have the smaller conceptual density. And who cares – they’re both tiny! Let’s add a
constructor, some variables, and methods. First in Python:
1 # Python
2 class Message:
3 greeting = 'Hello'
4
8 def say_hello(self):
9 return f'{self.greeting} {self.person}'
This class has a “constructor” with one argument, which is assigned as an instance attribute. The class attribute of
greeting is used in a method say_hello which returns an evaluated f-string.
How about the type hinting flavor for Python 3.5+?
1 # Python
2 class Message:
3 greeting = 'Hello'
4
3.11. Classes 15
Kotlin for Python Developers Documentation, Release 1.0.0
1 // Kotlin
2 class Message(val person: String) {
3 val greeting = "Hello"
4
That constructor syntax, right in the middle of the class name line, is unusual and cool. It helps to reduce the typing
versus Python’s constructor. We’ll go into more depth on this in the section on Classes.
17
Kotlin for Python Developers Documentation, Release 1.0.0
Conditionals
19
Kotlin for Python Developers Documentation, Release 1.0.0
20 Chapter 5. Conditionals
CHAPTER 6
when (x) {
!in 1..20 -> println(“x is 1”)
21,22 -> println(“x is 22 or 23”)
else -> {
// Some set of lines in a block
println(“x is greater than 22”)
}
}
6. etc.
generators, iterators
21
Kotlin for Python Developers Documentation, Release 1.0.0
Functions
1 import sys
2 from typing import List
3
9 if __name__ == '__main__':
10 main(sys.argv)
• Whereas Python terminates the function line with a colon and uses indentation for the block, Kotlin uses the
standard curly braces syntax
Python’s weird if __name__ block is ugly, and reveals a certain something about packaging being added after-the-
fact, but shows that Python is ready to just let you do damn fool stupid stuff at module scope. For instance, run your
program. Kotlin has a bit of a formal contract to meet when executing an “entry point”.
Note: Don’t like typing the boilerplate? PyCharm has a Live Template main for generating the run block at the
bottom. So does Kotlin. We’ll show this in the video for this segment.
Kotlin has another syntactic convenience: you aren’t required to say that the function returns nothing.
Function expressions
If using Python 3.5+ type hinting, that would be:
23
Kotlin for Python Developers Documentation, Release 1.0.0
Not too shabby. This will be a recurring point: we’ll compare Kotlin not just with “normal” Python, but also against
type-hinted-Python.
• Function argument typing and return value typing
24 Chapter 7. Functions
CHAPTER 8
Classes
Note: Python’s __init__ is called a constructor, but as its name implies, it is actually an initializer. The __new__
method is the factory.
8. Kotlin does some magic behind-the-scenes creation of Java classes named from the file name, because Java
needs classes
25
Kotlin for Python Developers Documentation, Release 1.0.0
26 Chapter 8. Classes
CHAPTER 9
27
Kotlin for Python Developers Documentation, Release 1.0.0
• genindex
• modindex
• search
29