Tomo.Log()


Kotlin/Swift correspondence table memo vol.1

[09/16, 2019]

Hi, it's Tomo. Recently I'm learning Kotlin to develop an Android app. Kotlin is similar to swift but there are many differences. So I just wanna left my memo to remind me to use those.

This may also help opposite case like learning Swift for Kotlin users.

var / let

Swift

 let name:String = "Tomo"
 var age:Int = 99 

Kotlin

 val name:String = "Tomo"
 var age:Int = 99

func is fun

I often mistake 'func' or 'fun'. Kotlin's one is 'fun'.

Swift

func createSomething(number:Int) -> Something {} 

Kotlin

fun createSomething(number:Int) : Something{} 

Computed value (getter / setter)

Swift

    var _cache:Int = 10
    var number : Int{
        get{
            return  self._cache
        }
        set(value){
            self._cache = value
        }
    }

Kotlin

 var _cache: Int = 10
 var number: Int
     get() = this._cache
     set(value) {
         this._cache = value
     }

Only getter

Swift

    var number : Int{
        get{
            return  10
        }
    }

Kotlin

 val number: Int
     get() = this._cache    

When you make the only getter in Kotlin, you have to use the 'val'. I took a long time to resolve compile error because I was using 'var' even computed value has only getter😅

Enum

enum -> enum class

Swift

   enum Animal {
      case Dog,
      case Cat
   }

Kotlin

enum class Animal {
    Dog, Cat
} 

nil is null

nil is called null in Kotlin(maybe it came from Java).

Force Unwrap

Swift

var optionalValue:Int?
var count = 1 + optionalValue!

Kotlin

var optionalValue:Int?
var count = 1 + optionalValue!!

Kotlin needs two '!!'.

Ternary operator for nil/null

Swift

let defaultValue : Int = 0
var count = optionalValue ?? defaultValue

Kotlin

val defaultValue : Int = 0
var count = optionalValue ?: defaultValue

Extension

Kotlin has no extension like a swift. So make public function is maybe the right way to do the same.

Swift

extension String {
 func newFunction(value:Int){
   //do somthing
 } 
}

Kotlin

fun String.newFunction(value:Int){
   //do somthing
}

switch clause

Kotlin doesn't have a switch clause. So use 'When' clause instead of it.

Swift

switch(animal){
 case .Dog:break 
 case .Cat:break 
 default:break
}

Kotlin

when(animal){
 .Dog -> {}
 .Cat -> {}
 else -> {}
}