1. 程式人生 > >Kotlin Android入門學習一

Kotlin Android入門學習一

Kotlin 是一種基於 JVM 的新的程式語言,由 JetBrains 開發,在 Apache 許可下已經開源;
主要優點有:開源、語言簡潔、安全、通用、互操作、句末不用分號、跟java互通!哈哈!
Konlin在Android studio 中應用:

1、下載Kotlin外掛:
   在Android studio - plugins下搜尋kotlin,install
2、在工程的根build.gradle檔案中新增Kotlin外掛的依賴
   classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:0.11.91' (版本看自己下載的,同下)
3
、配置modulebuild.gradle檔案 apply plugin: 'kotlin-android' compile 'org.jetbrains.kotlin:kotlin-stdlib:0.11.91'

通過選擇’Code’選單裡面的‘Convert Java File to Kotlin File’選項,
我們可以把當前的activity轉換成Kotlin類

Kotlin使用:
1、方法的定義
(fun 前,跟java一樣,公開的、保護的、私有的,不寫預設為公開的)

關鍵詞fun 方法名(引數)    返回型別(Unit為java的void,預設省略) {}

這裡寫圖片描述

2、簡單的小例子(參考官方的)

//程式入口
fun main(args: Array<String>) {
    println("Hello, world!")
}
//字串中需要列印引數,則需在引數前加$
//讀取args陣列下標為0的字串
fun main(args: Array<String>) {
    if (args.size == 0) {
        println("Please provide a name as a command-line argument")
        return
    }
    println("Hello, ${args[0]}!"
) } //迴圈列印陣列 fun main(args: Array<String>) { for (name in args) println("Hello, $name!") } //when的使用 類似java的switch,高富帥的通過,不符合的,呵呵 fun main(args: Array<String>) { val language = if (args.size == 0) "EN" else args[0] println( when (language) { "EN" -> "Hello!" "FR" -> "Salut!" "IT" -> "Ciao!" else -> "Sorry, I can't greet you in $language yet" }) } //呼叫類中的方法 class Greeter(val name: String) { fun greet() { println("Hello, ${name}"); } } fun main(args: Array<String>) { Greeter(args[0]).greet() } //注:Unit為java中的void //返回最大值函式: fun max(a: Int, b: Int) = if (a > b) a else b //空指標檢查 // Return null if str does not hold a number fun parseInt(str: String): Int? { try { return Integer.parseInt(str) } catch (e: NumberFormatException) { println("One of the arguments isn't Int") } return null } fun main(args: Array<String>) { if (args.size < 2) { println("No number supplied"); } else { val x = parseInt(args[0]) val y = parseInt(args[1]) // We cannot say 'x * y' now because they may hold nulls if (x != null && y != null) { print(x * y) // Now we can } else { println("One of the arguments is null") } } } //引數:任何型別的物件,返回字串的長度,型別不一致則返回空 fun getStringLength(obj: Any): Int? { if (obj is String) return obj.length // no cast to String is needed return null } //迴圈while使用 do..while一樣 fun main(args: Array<String>) { var i = 0 while (i < args.size) println(args[i++]) } //返回 Int型的函式 fun sum(a: Int, b: Int): Int { return a + b } //For迴圈遍歷任何提供了一個迭代器 fun main(args: Array<String>) { for (arg in args) println(arg) // or println() for (i in args.indices) println(args[i]) } //in的用法 fun main(args: Array<String>) { val x = Integer.parseInt(args[0]) //Check if a number lies within a range: val y = 10 if (x in 1..y - 1) println("OK") //Iterate over a range: for (a in 1..5) print("${a} ") //Check if a number is out of range: println() val array = arrayListOf<String>() array.add("aaa") array.add("bbb") array.add("ccc") if (x !in 0..array.size - 1) println("Out: array has only ${array.size} elements. x = ${x}") //Check if a collection contains an object: if ("aaa" in array) // collection.contains(obj) is called println("Yes: array contains aaa") if ("ddd" in array) // collection.contains(obj) is called println("Yes: array contains ddd") else println("No: array doesn't contains ddd") } //多型別描述定義 fun main(args: Array<String>) { val pair = Pair(1, "one") val (num, name) = pair println("num = $num, name = $name") } class Pair<K, V>(val first: K, val second: V) { operator fun component1(): K { return first } operator fun component2(): V { return second } } //定義實體類,使用類的屬性,看清楚類前有data!! data class User(val name: String, val id: Int) fun getUser(): User { return User("Alex", 1) } fun main(args: Array<String>) { val user = getUser() println("name = ${user.name}, id = ${user.id}") // or val (name, id) = getUser() println("name = $name, id = $id") // or println("name = ${getUser().component1()}, id = ${getUser().component2()}") } //遍歷整個map fun main(args: Array<String>) { val map = hashMapOf<String, Int>() map.put("one", 1) map.put("two", 2) for ((key, value) in map) { println("key = $key, value = $value") } } //實體類很碉堡的,類似java functions, toString(), equals(), hashCode() and copy(),getter、setter都預設有! data class User(val name: String, val id: Int) fun main(args: Array<String>) { val user = User("Alex", 1) println(user) // toString() val secondUser = User("Alex", 1) val thirdUser = User("Max", 2) println("user == secondUser: ${user == secondUser}") println("user == thirdUser: ${user == thirdUser}") // copy() function println(user.copy()) println(user.copy("Max")) println(user.copy(id = 2)) println(user.copy("Max", 2)) }

我比較喜歡kotlin的in,它既可以問候你一個,也可以問候your 伐木累

 //X為引數
 if (x in 1..10 )  
        println("OK")
 for(x in 1..10 )  
        println("你好:${x}")