This article focuses on the main similarities and differences between Swift and Kotlin, including implementation, style, syntax and other important details.
Note that in Swift, a switch statement must be exhaustive. In other words, a default clause is required if every single possible value of the condition hasn’t been tested. This is not the case in Kotlin
This is not enterely true in the case of Kotlin… If “when” is evaluated as an expression then it’s exhaustive as in Swift
I notice that in Kotlin, you don’t seem to be unwrapping optionals. Does it use a similar structure; i.e. an enum with non and some cases with associated data? I guess not.
There are two big differences between Kotlin and Swift:
In Kotlin everything is a reference, whereas in Swift you have references and values, which you covered.
In Kotlin interfaces are generic whereas in Swift protocols use associated types. Associated types are much more limited at present (though this might change). EG:
In Swift:
protocol Box {
associatedtype T
let value: T
}
let boxed: Box = … // Error, can’t have a variable of type Box because it has an associated type that you can’t specify.
protocol Box {
associatedtype T
let value: T
}
let boxed: Box = … // Error, can’t have a variable of type Box because it has an associated type that you can’t specify.
In Kotlin:
interface Box<T> {
val value: T
}
val boxed: Box<Int> = … // No prob.
You Explain very good similarities. Remember Every language have different approach to performing same task.
Data Class vs. Struct and val vs. let are wrong examples
Data Class in kotlin is value type, when you assign value of PersonOne to PersonTwo value you should use PersonOne.copy() function to make it value type but you directly assign to the other value.
val personOne = Person(“Jon”, “12 August”)
val personTwo = personOne.copy() // assign to another variable
personTwo.name = “Vanessa”
println(personOne.name) // prints Jon
println(personTwo.name) // prints Vanessa
val vs. let you should use listOf() in Kotlin to create list which provide immutable list, but you use mutableListOf() which already means you are using mutable list so it can be change later. val means it can never be re-initialized but it does’nt mean it’s inner value will not changeable.
val persons = listOf(Person(“Jon”, “12 August”),
Person(“Kim”, “10 July”),
Person(“Vanessa”, “12 August”),
Person(“Alisa”, “26 March”))
persons.add(Person(“Shaun”, “11 Jan”)) // compile time error
Great example overall.
However, I noticed a typo within the [ Kotlin — Null Safety] section. The [userID] parameter within the else clause should be camel cased to match its definition. Otherwise an error will occur. :
var id: Int? = 10
var userId = 0
if (id != null) {
userId = id
} else {
userID = -1
}
println(userID) //prints 10