Python to Kotlin
A brief syntax comparison between Kotlin and Python
Variable Assignment
This is basic variable assignment. In Kotlin we have mutable, where a variable can be changed. Immutable is where a variable cannot be changed. This is a compiler check, and not enforced in the JVM.
user = "Bob"
//Mutable
var user = "Bob"
//Immutable
val user = "Bob"
Lists
numbers = [1, 2, 3, 4, 5, 6]
//Immuatble List
val numbers = listOf(1, 2, 3, 4, 5, 6)
//Mutable List
var numbers = mutableListOf(1, 2, 3, 4, 5, 6)
Adding Items to List
numbers.append(7)
numbers += 7
numbers.add(7)
List Comprehension
>>> [n * 2
for n in [1, 2, 3, 4, 5, 6]]
[2, 4, 6, 8, 10, 12]
numbers.map { it * 2 }
Filter List
>>> filter(lambda x: (x % 2) == 0, numbers)
[2, 4, 6]
numbers.filter { (it % 2) == 0 }
List Iteration
>>> for n in numbers:
... print(n)
//Extension Loop Method
numbers.forEach {
println(it)
}
//Control Syntax
for (item in numbers) print(item)
Loop with Index
for i, num in enumerate(numbers):
print(i, num)
numbers.forEachIndexed { index, i ->
println("$index $i")
}
String Formatting
>>> "My Name is {} and I like {}".format("Bob", "Pie")
'My Name is Bob and I like Pie'
>>> "My Name is {name} and I like {food}".format(name="Jane", food="Cake")
'My Name is Jane and I like Cake'
val food = "Pie",
val name = "Bob"
//Standard String
val message = "My Name is $name and I like $food"
//With nested calls
val message = "My Name is $name and I Like ${food.toUpperCase()}"
Function Definition
>>> def add(x, y):
... return x + y
...
>>> add(1, 2)
3
fun add(x:Int, y:Int) : Int = x +y
fun add(x:Int, y:Int) : Int {
return x +y
}
Lambda
multiply_by_two = lambda x: x * 2
// Explicit parameter declaration
multiplyByTwo = { x -> x * 2}
// Implicit parameter declaration
multiplyByTwo = { it * 2 }
Partial Application
from functools import partial
from collections import namedtuple
from time import time
metric = namedtuple("Metric",
["value", "timestamp", "metric", "unit"])
loaded_metric = partial(metric, metric="Weight", unit="lb")
current_weight = loaded_metric(value=179, timestamp=time())
import kotlin.js.Date
data class Metric(
val value : Number,
val timestamp : Date,
val metric : String,
val unit : String
)
val loadedMetric = { value, timestamp ->
Metric(value = value, timestamp = timestamp, metric="Weight", unit="lb")
}
loadedMetric(179, Date.now())
Ternary Conditions
1 if True is True else False
// Standard Ternary
val x = if (true is true) 1 else 0
// We can also support more complex
val number = if (x < 10) {
1
} else if ( x < 20) {
10
} else if ( x < 30) {
20
} else {
0
}
None/Null Checking
if x is not None:
return 1
// Standard If Statement
if (x != null) 1
// If x is null default to 1
val rsp = x ?: 1
Dictionary Checking
map = {
"one": 1,
"two": 2
}
if "one" in map:
return map["one"]
map.get("one", 0)
val map = mapOf("one" to 1, "two" to 2)
//If conditional approach
if ("one" in map) map["one"] else 0
//Takes if key present if not return default of 0
map.takeIf { it.contains("one") }?.get("one") ?: 0
//Get with a default
map.getOrElse("one", 0)
//When Statement
when {
"one" in map -> map["one"]
else -> 0
}
Pattern Matching Statement
Not supported
...
enum class HTTPVerbs {
GET, POST, PUT, UPDATE, DELETE
}
//Explicit for each cast
fun test(verb: HTTPVerbs) {
when(verb) {
HTTPVerbs.GET -> TODO()
HTTPVerbs.POST -> TODO()
HTTPVerbs.PUT -> TODO()
HTTPVerbs.UPDATE -> TODO()
HTTPVerbs.DELETE -> TODO()
}
}
//Chaining conditions together
fun test(verb: HTTPVerbs) {
when(verb) {
HTTPVerbs.GET, HTTPVerbs.POST -> TODO()
HTTPVerbs.UPDATE, HTTPVerbs.DELETE -> TODO()
HTTPVerbs.PUT -> TODO()
}
}