iT邦幫忙

2022 iThome 鐵人賽

DAY 1
0
Software Development

Kotlin on the way系列 第 1

Day 1 everything you need to know about Kotlin 你應知道的 Kotlin

  • 分享至 

  • xImage
  •  

Let's learn to walk before we run.
Fifty shades Darker

中文在下面,ithome 不支持 #中文語法QQ

Seriously, you should know all the basic syntax before reading this series, just like your should learn walk before learn how to run, so I sum up all the basic syntax, please check it out

kotlin basic syntax
for better understanding, it will be great if you are familiar with all the detail in the concept topics, I will use this article to point out part of the basic knowledge you should know, and from tomorrow, we will guide through the concept and design in OOP

variable

basically you can declare variable in three way

val hello = "long"
var hello2 = "live"
const val hello3 = "Kotlin"

the difference between those is the restrict of getter and setter, var has both getter and setter, you can read/ write as long as you can attach it, on the other side, val doesn't have a setter, but it still could be mutable, we can do thing like this

val test:Int 
    get() = speed * 2
private var speed = 1

so everytime you read the test value, it will execute what defined in it getter, therefore if we change the value of speed, the test will return different value

and const val is easier, we can consider it as static valuable, it will exists as always, and it can't be changed

function

in kotlin we can define a scope of program and wrap it as function

fun myFunction(){
    println("I am looking for remote job or freelancer project,, please dm me")
}

and we can pass a function to a function

fun lookForRemote(block:() -> Unit){
    block.invoked()
}

lookForRemote(::myFunction)

and things in the parameter is something called lambda, currently is pass nothing and return Unit, but it can also look like, so we can define a function to a variable

val amount:(Long) -> Int

and function doesn't always require name, we could define an anonymous function

val tmp = fun(i:Int):String{
    return i.toString()
}

loop

loop is basic control flow of programming, in kotlin we can use while loop and. for loop, thing you should aware is for loop is not equal to forEach, especially the return and jump condition

for(item in collection)
for(index in collection.indice)
for(i in 1..5)
for(i in 10 downTo 0 step 2)
for((first, second) in listOf(Pair(1,0)))
while(a > 0){
    a--
}

do {
    a--
} while(a > 0)

condition

condition is another topic you should familiar, we have some kotlin syntax can use such in in range, tye check, enum, sealed encapsulate

when(num){
    1 -> {}
    2, 3 -> {}
    in 4..10-> {}
    else -> {}
}

when (request){
    is Success ->{}
    is Fail -> {}
}

class

Kotlin is work for function programming style and object orientation program style, and for me personally I like the design of Kotlin in OOP, class is the basic knowledge of it, include the constructor, named arguments

class Test{
    
}

class Car(brand:String){
    
}
class Car {
    constructor(brand:String){
        
    }
}
object Model {
    
}

nullish

nullish is important but also convenient in Kotlin, unlike Java, Kotlin handles null elegantly and properly, beside ?? ?: !!, we can also check it in condition, the once we did that, the ide can smart cast the variable is not null anymore in a scope, however in some condition it won't work since the mutability, we will cover that in the following articles

var num:Int? = null
num?.let(::print)
num ?: 0
num ?: return
num ?: throw Exception("invalid input")
num !!

I just cover some topic of Kotlin above, basically this article is suit in all level, whether to learn how to design Kotlin program, or just review what you already know

中文

這系列文章,儘管是全階段的開發者都適合閱讀,但基本上,最少也得了解並熟悉基礎語法,就好比你應在學會跑之前先學會走路,所以我在這裡整理的一些基礎知識

kotlin basic syntax

為了更好地理解之後的文章,最好是以熟悉所有基礎語法後再去閱讀,而我會在這篇文章中,簡要的點出一些基礎知識,從明天開始,會逐步帶入物件導向的設計和原則

variable

基本上,你可以用三種方式聲明變數

val hello = "long"
var hello2 = "live"
const val hello3 = "Kotlin"

三中之間的不同在於, getter/ setter 的限制性, var 同時擁有 getter/ setter,只要你可以存取這個變數,便可以對他做讀取寫入
而 val 只有 getter 但這並不保證了他無法被修改,如下面的範例

val test:Int 
    get() = speed * 2
private var speed = 1

都我們的 getter 被定義成一個邏輯運算,每去讀取時,都會執行一次該邏輯,換句話說,每次讀取,他都會依照當下時序的程式狀態運算,而裡面有任何的可變點時,val 的值就不會是固定的

const val 更簡單一點,我們可以簡單地將其視為靜態變數,當你程式運行的時候,他就在那裡,且無法被改變了

function

我們可以將一個區段的程式包裝成一個函式

fun myFunction(){
    println("I am looking for remote job or freelancer project, please dm me")
}

我們同樣可以把函式傳給函式

fun lookForRemote(block:() -> Unit){
    block.invoked()
}

lookForRemote(::myFunction)

現在在函式參數的定義叫做 lambda,現在 lambda 沒有傳入或是傳出值,但我可以給給他定義,並指派給一個變數作為函式

val amount:(Long) -> Int

另一方面,有個東西叫做匿名函式

val tmp = fun(i:Int):String{
    return i.toString()
}

loop

迴圈是基本的控制流工具,在柯特林我們可以使用 for , while 迴圈,值得注意的是 for loop 和 forEach 的操作有一點不同,尤其在 return 和 jump 的時候

for(item in collection)
for(index in collection.indice)
for(i in 1..5)
for(i in 10 downTo 0 step 2)
for((first, second) in listOf(Pair(1,0)))
while(a > 0){
    a--
}

do {
    a--
} while(a > 0)

condition

條件判斷是程式的另一個基礎,除了多數語言通用的比較法,在 Kotlin 裡面,我們可以用語法糖簡化比較方式,像是範圍比較,enum, sealed class等封裝

when(num){
    1 -> {}
    2, 3 -> {}
    in 4..10-> {}
    else -> {}
}

when (request){
    is Success ->{}
    is Fail -> {}
}

class

Kotlin 可以以函式編程或是物件導向兩種風格編寫,我個人喜歡Kotlin 在物件導向的設計,而類別就是其中最基本的知識,包含了建構子,具名參數等

class Test{
    
}

class Car(brand:String){
    
}
class Car {
    constructor(brand:String){
        
    }
}
object Model {
    
}

nullish

null 的處理很重要,但在Kotlin 裡面也很簡單,和 Java 不同,我們原生語法就對其有很好的支持,可以使用? ?: !!的語法,我們也能為其使用條件判斷,在某些情境,ide 會知道後面的某個範圍內該變數不會是空的,但有時會因為可變性的關係,而無法安全的確認,這會在之後的文章提到

var num:Int? = null
num?.let(::print)
num ?: 0
num ?: return
num ?: throw Exception("invalid input")
num !!

我只包含了一些主題,基本上這篇文章適合全等級的人看看,不論是來學Kotlin 語言如何設計程式,或是來複習你忘記的知識


下一篇
Day2 Design of project 專案設計
系列文
Kotlin on the way31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言