Koltin-用法總結__java

來源:互聯網
上載者:User
1. Kotlin配置

點擊功能表列的“Tools”選項,選擇“Kotlin”,然後選擇“Configure Kotlin in Project”。如下圖所示。 
 
在彈出的視窗中選擇需要使用Kotlin的模組和Kotlin編譯器和運行時的版本,如下圖所示。

 
點擊“OK”之後,Kotlin外掛程式會自動開始配置。配置完成之後,同步一下工程(Sync Project)即可。

推薦配置:開啟模組下的build.gradle檔案,在apply plugin: ‘kotlin-android’下面加入一行:apply plugin: ‘kotlin-android-extensions’。這是一個Kotlin的擴充模組,可以讓Activity自動關聯xml布局中的View而不需要findViewById。 2. Anko的使用

在官方庫Anko的支援下,有了很多變化 2.1 向findViewById告別

val onlyTv = find<TextView>(R.id.onlyTv)val onlyTv: TextView = find(R.id.onlyTv)
1 2

在匯入一個外掛程式kotlin-android-extensions,變得更簡單了 
直接使用在布局中定義的id為hello的這個textView 2.2 簡單粗暴的startActivity

//原本的樣子Intent intent = new Intent(LoginActivity.this, MainActivity.class);intent.putExtra("name", "張三");intent.putExtra("age", 27);startActivity(intent);//在Kotlin中的表現startActivity<MainActivity>()startActivity<MainActivity>("name" to "張三", "age" to 27)startActivityForResult<MainActivity>(101, "name" to "張三", "age" to 27)
1 2 3 4 5 6 7 8 9 10 11

2.3 封裝Toast

//原來樣子Toast.makeText(context, "this is a toast", Toast.LENGTH_SHORT).show();//現在樣子context.toast("this is a toast")
1 2 3 4 2.4 DSL編程(接下來補充) 2.5 簡化非同步作業

 
//有了Anko的配合,蜜汁縮排 
Alt text 2.6 簡化日誌列印

實現AnkoLogger這個介面,方便列印日誌 

Tag為所在類的類名 3. 其他方法 3.1 用apply方法進行資料群組合

//例如//建立三個類class A(val b: B)class B(val c: C)class C(val content: String)//用Java方法進行資料群組合C c = new C("content");B b = new B(c);A a = new A(b);//使用apply方法進行資料群組合val a = A().apply {    b = B().apply {        c = C("content")    }}//在DSL編程匯中的寫法layout.addView(TextView(context).apply {    text = "這是常值內容"    textSize = 16f})
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

只需聲明一個變數。這裡我們只聲明了一個 a 對象,然後初始化了一個 A,在這個初始化的對象中先給 B 賦值,然後再提交給了 a。 3.2 利用擴充類代替工具類

我做字串判斷的時候一定會寫一個工具類,在這個工具類裡充斥著各種各樣的判斷方法。而在 Kotlin 中,可以用擴充方法來替代。

//String的擴充類fun String.isName(): Boolean {    if (isEmpty() || length > 10 || contains(" ")) {        return false    }    val reg = Regex("^[a-zA-Z0-9\u4e00-\u9fa5]+$")    return reg.matches(this)}fun String.isPassword(): Boolean {    return length in 6..12}fun String.isNumber(): Boolean {    val regEx = "^-?[0-9]+$"    val pat = Pattern.compile(regEx)    val mat = pat.matcher(this)    return mat.find()}...println("張三".isName())println("123abc".isPassword())println("123456".isNumber())//ImageView的擴充類fun ImageView.displayUrl(url: String?) {    if (url == null || url.isEmpty() || url == "url") {        imageResource = R.mipmap.ic_launcher    } else {        Glide.with(context)                .load(ColumnServer.SERVER_URL + url)                .into(this)    }}...val imageView = findViewById(R.id.avatarIv) as ImageViewimageView.displayUrl(url)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 3.3 委託/代理,SharedPreference 不再麻煩(還需要研究) 3.4 資料類的自動getter/setter及class簡潔的寫法

//Java代碼

class Person {    private String name;    public Person(String name) {        this.name = name;    }    public void setName(String name) {        this.name = name;    }    public void getName() {        return name;    }}Person person = new Person("張三");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

//Kotlin代碼

class Person(var name: String)val person = Person("張三")//添加預設值class Person(var name: String = "張三")val person = Person()
1 2 3 4 5 3.5 實現單例

//Java中單例

public class Singleton {    private static Singleton instance = null;    private Singleton(){    }    private synchronized static void createInstance() {        if (instance == null) {            instance = new Singleton();        }    }    public static Singleton getInstance() {        if (instance == null) createInstance();        return instance;    }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

//而在Kotlin中,只用一句話表示

object Singleton{}
1 3.6 容器的操作符(接下來補充) 3.7 with的用法

with函數是一個單獨的函數,並不是Kotlin中的extension,所以調用方式有點不一樣,返回是最後一行,然後可以直接調用對象的方法

當一個對象執行個體需要調用多個方法

fun alphabet(): String {    val stringBuilder = StringBuilder()    return with(stringBuilder) {        for (letter in 'A'..'Z') {            this.append(letter)        }        append("\nNow I know the alphabet!")        this.toString()    }}
1 2 3 4 5 6 7 8 9 10 3.8 伴生對象

每個類都可以實現一個伴生對象,它是該類的所有執行個體共有的對象。它將類似於Java中的靜態欄位。

class App : Application() {    companion object {    //lateinit表示這個屬性開始是沒有值得,但是,在使用前將被賦值        lateinit var instance: App        //private set用於說明外部類不能對其進行賦值。            private set    }    override fun onCreate() {        super.onCreate()        instance = this    }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 3.9 建立匿名類的實現
recycler.adapter = object : RecyclerView.Adapter() {    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {    }    override fun getItemCount(): Int {    }    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {    }}
1 2 3 4 5 6 7 8 9 10 11 3.10 最終類

使用sealed關鍵字修飾

sealed class SealedClassTest {    object getStop : Opertion()    object getStart : Opertion()}
1 2 3 4 5 3.11 延遲屬性
val emails by lazy { loadEmails(this) }
1 2 3.12 委託類/代理屬性(by)

Kotlin-代理屬性(by)

使用by關鍵字 
`使用了委託模式:為其他對象提供了一種代理以控制這個對象的訪問 
- 消極式載入屬性(lazy property): 屬性值只在初次訪問時才會計算, 
- 可觀察屬性(observable property): 屬性發生變化時, 可以向監聽器發送通知, 
- 將多個屬性儲存在一個 map 內, 而不是儲存在多個獨立的域內.

//Kotlin中,委託的實現依靠於關鍵字 by ,by表示將抽象主題的執行個體(by後邊的執行個體)儲存在代理類執行個體的內部,比如SportsManager類繼承於ISports介面,並可以ISports介面的所有的 public 方法委託給一個指定的對象。interface ISports {    fun doSports()}class SwimForSports: ISports{    override fun doSports() {        println("do swim")    }}class SportsManager(sport: ISports): ISports by sportfun main(args: Array<String>) {    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.