Kotlin
Basic Syntax
Swift
|
Package definition and imports
|
package my.demo
import kotlin.text.*
// ...
|
import Fondation
|
Program entry point
|
fun main() {
println("Hello world!")
}
|
Code written at global scope is used as the entry point for the program, so you don’t need a main() function.
|
Functions
|
fun sum(a: Int, b: Int): Int {
return a + b
}
|
func sum(a: Int, b: Int) -> Int {
return a + b
}
|
fun sum(a: Int, b: Int) = a + b
|
func sum(a: Int, b: Int) {
a + b
}
|
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
|
func printSum(a: Int, b: Int) -> Void {
print("sum of \(a) and \(b) is \(a + b)")
}
|
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
|
func printSum(a: Int, b: Int) {
print("sum of \(a) and \(b) is \(a + b)")
}
|
Variables
|
val a: Int = 1 // immediate assignment
val b = 2 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
|
let a: Int = 1 // immediate assignment
let b = 2 // `Int` type is inferred
let c: Int // Type required when no initializer is provided
c = 3 // deferred assignment
|
var x = 5 // `Int` type is inferred
x += 1
|
var x = 5 // `Int` type is inferred
x += 1
|
val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
|
let PI = 3.14
var x = 0
func incrementX() {
x += 1
}
|
Comments
|
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
|
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
|
/* The comment starts here
/* contains a nested comment */
and ends here. */
|
/* The comment starts here
/* contains a nested comment */
and ends here. */
|
String templates
|
var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
|
import Foundation
var a = 1
// simple name in template:
let s1 = "a is \(a)"
a = 2
// arbitrary expression in template:
let s2 = "\(s1.replacingOccurrences(of: "is", with: "was")), but now is \(a)"
|
Conditional expressions
|
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
|
func maxOf(a: Int, b: Int) -> Int {
if (a > b) {
return a
} else {
return b
}
}
|
fun maxOf(a: Int, b: Int) = if (a > b) a else b
👏
|
func maxOf(a: Int, b: Int) -> Int {
a > b ? a : b
}
|
Nullable values and null checks
|
fun parseInt(str: String): Int? {
// ...
}
|
func parseInt(str: String) -> Int? {
// ...
}
|
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("'$arg1' or '$arg2' is not a number")
}
}
|
func printProduct(arg1: String, arg2: String) {
let x = parseInt(arg1)
let y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != nil && y != nil) {
// x and y are automatically cast to non-nullable after null check
print(x * y)
}
else {
print("'\(arg1)' or '\(arg2)' is not a number")
}
}
|
// ...
if (x == null) {
println("Wrong number format in arg1: '$arg1'")
return
}
if (y == null) {
println("Wrong number format in arg2: '$arg2'")
return
}
// x and y are automatically cast to non-nullable after null check
println(x * y)
👏
|
// ...
if (x == nil) {
print("Wrong number format in arg1: '\(arg1)'")
return
}
if (y == nil) {
print("Wrong number format in arg2: '\(arg2)'")
return
}
// x and y force unwrap
print(x! * y!)
//or
guard let x = x else {
print("Wrong number format in arg1: '\(arg1)'")
return
}
guard let y = y else {
print("Wrong number format in arg2: '\(arg2)'")
return
}
print(x * y)
|
Type checks and automatic casts
|
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}
|
func getStringLength(obj: Any) -> Int? {
if let obj = obj as? String {
return obj.count
}
return nil
}
|
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
|
func getStringLength(obj: Any) -> Int? {
guard let obj = obj as? String else { return nil }
return obj.count
}
//or
func getStringLength(obj: Any) -> Int? {
(obj as? String)?.count
}
|
fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
|
func getStringLength(obj: Any) -> Int? {
if let obj = obj as? String, obj.count > 0 {
return obj.count
}
return nil
}
|
for loop
|
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
|
let items = ["apple", "banana", "kiwifruit"]
for item in items {
print(item)
}
|
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
|
let items = ["apple", "banana", "kiwifruit"]
for index in items.indices {
print("item at \(index) is \(items[index])")
}
|
while loop
|
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
|
let items = ["apple", "banana", "kiwifruit"]
var index = 0
while index < items.count {
print("item at \(index) is \(items[index])")
index += 1
}
|
when expression
|
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
👏
|
func describe(obj: Any) -> String {
switch obj {
case 1 as Int: //or case is Int where obj as? Int == 1
return "One"
case "Hello" as String: //or case is String where obj as? String == "Hello":
return "Greeting"
case is Double:
return "Double"
case _ where !(obj is String):
return "Not a string"
default:
return "Unknown"
}
}
|
Ranges
|
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
|
let x = 10
let y = 9
if 1...y+1 ~= x {
print("fits in range")
}
|
val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range, too")
}
|
let list = ["a", "b", "c"]
if !(0..<list.count ~= -1) {
print("-1 is out of range")
}
if !(list.indices ~= list.count) {
print("list size is out of valid list indices range, too")
}
|
for (x in 1..5) {
print(x)
}
|
for x in 1...5 {
print(x)
}
|
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
|
for x in stride(from: 1, through: 10, by: 2) {
print(x)
}
print()
for x in stride(from: 9, through: 0, by: -3) {
print(x)
}
|
Collections
|
for (item in items) {
println(item)
}
|
for item in items {
print(item)
}
|
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
👏
|
if items.contains("orange") {
print("juicy")
}else if items.contains("apple") {
print("apple is fine too")
}
|
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
|
let fruits = ["banana", "avocado", "apple", "kiwifruit"]
fruits
.filter { $0.starts(with: "a") }
.sorted()
.map { $0.uppercased() }
.forEach { print($0) }
|
Creating basic classes and their instances
|
val rectangle = Rectangle(5.0, 2.0)
val triangle = Triangle(3.0, 4.0, 5.0)
|
let rectangle = CGSize(width: 5.0, height: 2.0)
struct Triangle {
let a, b, c: CGFloat
}
let triangle = Triangle(a: 3.0, b: 4.0, c: 5.0)
|