TechTalk đã tổng hợp và so sánh mọi thứ trong code của Swift vs Kotlin. Và từ đó thấy sự tường đồng đến bất ngờ của 2 ngôn ngữ này mà ae developer nên biết trước khi muốn học thêm iOS hay Android.
Kotlin vs Swift – Android và iOS cùng hướng tới việc tạo ra một ngôn ngữ universal.”]
Swift | Kotlin |
print(“Hello, world!”) | println(“Hello, world!”) |
Swift | Kotlin |
var myVariable = 42 myVariable = 50 let myConstant = 42 |
var myVariable = 42 myVariable = 50 val myConstant = 42 |
Swift | Kotlin |
let explicitDouble: Double = 70 | val explicitDouble: Double = 70.0 |
Swift | Kotlin |
let label = “The width is “ let width = 94 let widthLabel = label + String(width) |
val label = “The width is “ val width = 94 val widthLabel = label + width |
Swift | Kotlin |
let apples = 3 let oranges = 5 let fruitSummary = “I have (apples + oranges) ” + “pieces of fruit.” |
val apples = 3 val oranges = 5 val fruitSummary = “I have ${apples + oranges} ” + “pieces of fruit.” |
Swift
1
2
3
4
5
6
7
8
9
10
11
|
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..
print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
|
val names = arrayOf("Anna", "Alex", "Brian", "Jack")
val count = names.count()
for (i in 0..count - 1) {
println("Person ${i + 1} is called ${names[i]}")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
|
Swift
1
2
3
4
5
6
7
8
9
10
|
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
|
Kotlin
1
2
3
4
5
6
7
8
9
10
|
for (index in 1..5) {
println("$index times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
|
Arrays
Swift | Kotlin |
var shoppingList = [“catfish”, “water”, “tulips”, “blue paint”] shoppingList[1] = “bottle of water” |
val shoppingList = arrayOf(“catfish”, “water”, “tulips”, “blue paint”) shoppingList[1] = “bottle of water” |
Maps Swift
Swift | Kotlin |
var occupations = [ “Malcolm”: “Captain”, “Kaylee”: “Mechanic”, ] occupations[“Jayne”] = “Public Relations” |
val occupations = mutableMapOf( “Malcolm” to “Captain”, “Kaylee” to “Mechanic” ) occupations[“Jayne”] = “Public Relations” |
Empty Collections
Swift | Kotlin |
let emptyArray = [String]() let emptyDictionary = [String: Float]() |
val emptyArray = arrayOf() val emptyMap = mapOf() |
Swift
1
2
3
4
5
6
|
func greet(_ name: String,_ day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Cafedev.vn", "Tuesday")
|
Kotlin
1
2
3
4
5
6
|
fun greet(name: String, day: String): String {
return "Hello $name, today is $day."
}
greet("Cafedev.vn", "Tuesday")
|
Swift
1
2
3
4
5
|
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
|
Kotlin
1
2
3
4
5
|
data class GasPrices(val a: Double, val b: Double,
val c: Double)
fun getGasPrices() = GasPrices(3.59, 3.69, 3.79)
|
Swift
1
2
3
4
5
6
7
8
9
10
|
func sumOf(_ numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf(42, 597, 12)
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
13
|
fun sumOf(vararg numbers: Int): Int {
var sum = 0
for (number in numbers) {
sum += number
}
return sum
}
sumOf(42, 597, 12)
// sumOf() can also be written in a shorter way:
fun sumOf(vararg numbers: Int) = numbers.sum()
|
Swift
1
2
3
4
5
6
7
8
9
10
|
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
let increment = makeIncrementer()
increment(7)
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
13
|
fun makeIncrementer(): (Int) -> Int {
val addOne = fun(number: Int): Int {
return 1 + number
}
return addOne
}
val increment = makeIncrementer()
increment(7)
// makeIncrementer can also be written in a shorter way:
fun makeIncrementer() = fun(number: Int) = 1 + number
|
Swift | Kotlin |
let numbers = [20, 19, 7, 12] numbers.map { 3 * $0 } |
val numbers = listOf(20, 19, 7, 12) numbers.map { 3 * it } |
Swift | Kotlin |
var mutableArray = [1, 5, 3, 12, 2] mutableArray.sort() |
listOf(1, 5, 3, 12, 2).sorted() |
Swift
1
2
3
4
5
6
|
func area(width: Int, height: Int) -> Int {
return width * height
}
area(width: 2, height: 3)
|
Kotlin
1
2
3
4
5
6
7
8
|
fun area(width: Int, height: Int) = width * height
area(width = 2, height = 3)
// This is also possible with named arguments
area(2, height = 2)
area(height = 3, width = 2)
|
Swift
1
2
3
4
5
6
7
8
|
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
|
Kotlin
1
2
3
4
5
6
7
|
class Shape {
var numberOfSides = 0
fun simpleDescription() =
"A shape with $numberOfSides sides."
}
|
Sử dụng
Swift
1
2
3
4
5
|
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
|
Kotlin
1
2
3
4
5
|
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
|
Swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
class NamedShape {
var numberOfSides: Int = 0
let name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
self.numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length " +
sideLength + "."
}
}
let test = Square(sideLength: 5.2, name: "square")
test.area()
test.simpleDescription()
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
open class NamedShape(val name: String) {
var numberOfSides = 0
open fun simpleDescription() =
"A shape with $numberOfSides sides."
}
class Square(var sideLength: BigDecimal, name: String) :
NamedShape(name) {
init {
numberOfSides = 4
}
fun area() = sideLength.pow(2)
override fun simpleDescription() =
"A square with sides of length $sideLength."
}
val test = Square(BigDecimal("5.2"), "square")
test.area()
test.simpleDescription()
|
Swift
1
2
3
4
5
6
7
8
9
10
11
12
|
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
|
var movieCount = 0
var songCount = 0
for (item in library) {
if (item is Movie) {
++movieCount
} else if (item is Song) {
++songCount
}
}
|
Swift
1
2
3
4
5
6
7
8
9
10
|
let nb = 42
switch nb {
case 0...7, 8, 9: print("single digit")
case 10: print("double digits")
case 11...99: print("double digits")
case 100...999: print("triple digits")
default: print("four or more digits")
}
|
Kotlin
1
2
3
4
5
6
7
8
9
10
|
val nb = 42
when (nb) {
in 0..7, 8, 9 -> println("single digit")
10 -> println("double digits")
in 11..99 -> println("double digits")
in 100..999 -> println("triple digits")
else -> println("four or more digits")
}
|
Downcasting
1
2
3
4
5
6
7
8
|
for current in someObjects {
if let movie = current as? Movie {
print("Movie: '\(movie.name)', " +
"dir. \(movie.director)")
}
}
|
Kotlin
1
2
3
4
5
6
7
8
|
for (current in someObjects) {
if (current is Movie) {
println("Movie: '${current.name}', " +
"dir. ${current.director}")
}
}
|
Swift
1
2
3
4
5
6
7
8
9
|
protocol Nameable {
func name() -> String
}
func f(x: T) {
print("Name is " + x.name())
}
|
Kotlin
1
2
3
4
5
6
7
8
9
|
interface Nameable {
fun name(): String
}
fun f(x: T) {
println("Name is " + x.name())
}
|
Swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
|
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
val Double.km: Double get() = this * 1000
val Double.m: Double get() = this
val Double.cm: Double get() = this / 100
val Double.mm: Double get() = this / 1000
val Double.ft: Double get() = this / 3.28084
val oneInch = 25.4.mm
println("One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.0.ft
println("Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"
|
Tương lại không xa ae developer iOS vs Android có thể nói chuyện với nhau một cách dễ dàng hơn trong code và dev app. Vì có quá nhiều sự tương đồng.
Devmaster Academy via CafeDev