Designed by IntelliJ (first released 2011) as a modern replacement to Java, with a less verbose syntax and with support for a more functional style of programming (immutability, higher-order functions, and type inference).
In 2017, Google declared Kotlin an official language for Android development.
@file:JvmName("Main")
// Name of the Java class as the function below is in global scope
fun main(args: Array<String>) {
println("Hello, World!")
}
Variables:
var name: String = "Adam"- Use
valfor constants
- Use
Types:
Double,Float,Long,Int,Short,Byte,Char,Boolean- Type can be inferred from context
- Type conversions must be explicit
- e.g.
someInt.toLong() - When declaring a float, append the value with an
fe.g.val zero: Float = 0f
- e.g.
String templating:
"${someExpression}"syntax for templating"$someVariable"shorthand when referring to variables
Collections:
Array: fixed size, mutableList: fixed size, immutableMutableList: variable size, mutable- Create inline array using
arrayOf('a', 'b', 'c')
Conditional statements
- Single-line statements can be used like a ternary statement
if someCondition someValue else otherValue- Can use braces for multi-line statements
- Value of the last statement in the block is used as the return value of block (the value ‘yielded’ by the block)
Switch:
-
val numDays = when (month) { 1, 3, 5, 7, 8, 10, 12, -> 31 2 -> 28 else -> 30 }``` -
val quadrant = when { x > 0 && y > 0 -> "I" x <= 0 && y > 0 -> "II" x <= 0 && y <= 0 -> "III" x > 0 && y <= 0 -> "IV" else -> "None" }``` - Can also use
in min..maxfor number ranges
Functions:
fun name(param1: Type, param2: Type): ReturnType {
}
fun singleLine() = Random.nextInt(100)
Classes:
class Point(x: Float, y: Float) {
var x: Float = x
var y: Float = y
// Can also use `val` for constants
}
// Same variable name used in constructor argument and
// property name, so can simply exclude property definition
class Point(var x: Float, var y: Float) {
}
class Point(var x: Float, var y: Float) {
override fun toString = "($x, $y)"
}
Getters and setters:
// Within a class block
val computedProperty: Int
get() {
return ...
}
var name: String
set(value) {
println("Name changed from '$field' to '$value'")
field = value
// if `name` is used instead of `field`, it would cause an infinite loop
}
Lambdas:
{ param1: Type, param2: Type ->
body
}
// If lambda is the last parameter, Swift-like syntax to put it outside the braces:
intArrayOf(3, 1, 4, 1).forEach { x -> println(x) }