4 ms·
The article is missing the similarities between Swift Optionals and Kotlin Nullables. Swift code: var name: String? name? ///returns a safe value name!
by Unknoob 9y ago
The article is missing the similarities between Swift Optionals and Kotlin Nullables.
Swift code:
var name: String?
name? ///returns a safe value
name! ///returns an unsafe value and throws an exception in case of a nil value
if name != nil {
///Now we can use name! forcing unwrap because we know it's not nil
}
if let unwrapedName = name {
/// Here we can use unwrapedName without forcing the unwrap
}
The null checks are almost the same in Kotlin: https://kotlinlang.org/docs/reference/null-safety.html https://kotlinlang.org/docs/reference/null-safety.html
- jorgemf 9y agokotlin make it a bit simpler, once you do name != null you can use it as it is never null after than, there is not need to use let. It makes it more readable.
- flaie 9y agoIn kotlin you can also write: var name: String? // some code name?.let { // here name is not nil and can be accessed via variable "it" } // or name?.let { name -> // here name shadows the previous variable, and is not nil }