美文网首页Kotlin学习
Kotlin快速入门文档和习惯用法

Kotlin快速入门文档和习惯用法

作者: GexYY | 来源:发表于2018-11-21 09:42 被阅读0次

    Kotlin的基本语法和习惯用法,能够快速入门的中文文档

    http://www.kotlindoc.cn/

    项目中的习惯用法

    when适当的代替if...else...

    //when写法
    when {
        it.isHasTask() -> {
            if (!it.isPlaying()) it.playOrPauseWithBackGround()
            toAudioPlayActivity(this@MainActivity, mCode, mCurPlayingId, true)
        }
        else -> {
            var cCode = QmSpHelper.latestRecordCode()
            if (!TextUtils.isEmpty(cCode)) toAudioPlayActivity(this@MainActivity, cCode, "", false)
        }
    }
    
    //if...else...写法
    if (it.isHasTask()) {
        if (!it.isPlaying()) it.playOrPauseWithBackGround()
        toAudioPlayActivity(this@MainActivity, mCode, mCurPlayingId, true)
    } else {
        var cCode = QmSpHelper.latestRecordCode()
        if (!TextUtils.isEmpty(cCode)) toAudioPlayActivity(this@MainActivity, cCode, "", false)
    }
    

    when代替switch

    override fun onClick(v: View?) {
            when (v?.id) {
                R.id.aboutServiceProtocol -> {
                    toWebViewActivity(this@AboutUsActivity, USER_SERVICE_AGREEMENT_URL)
                }
                R.id.aboutPayProtocol -> {
                    toWebViewActivity(this@AboutUsActivity, USER_PAY_AGREEMENT_URL)
                }
                R.id.aboutPrivacyProtocol -> {
                    toWebViewActivity(this@AboutUsActivity, USER_PRIVACY_POLICY_URL)
                }
                R.id.aboutCopyrightInfo -> {
                    toWebViewActivity(this@AboutUsActivity, USER_COPYRIGHT_URL)
                }
            }
        }
    

    静态变量和静态方法

    companion object {
            const val PLAY = "com.qm.music.play"
            const val PAUSE = "com.qm.music.pause"
            const val PREVIOUS = "com.qm.music.previous"
            const val NEXT = "com.qm.music.next"
            const val CLOSE = "com.qm.music.close.notify"
            const val LOGOUT_CLOSE = "com.qm.music.logout.close.notify"
            const val NOTIFY_ID = 22
            private const val MSG_UPDATE_PROGRESS = 1
    
            const val ERROR_API = 1//接口出错
            const val ERROR_MEDIA = 0//播放器错误
            const val ERROR_EMPTY = 3//播放内容为空
            
            fun pause(){}//静态方法
        }
    

    let,with,apply,run的使用

    • 区别
    • 非空判断的let使用
    entity?.let {
                 callBack.onSuccess(it)
                } ?: let {
                 callBack.onError()
                }
    
    • 三目运算
    //常规写法
    val z=if(x>y) { x } else { y }
    
    //let写法
    val entity=response?.let { 
                            it.body()
                        }?:let{
                            null
                        }   
    
    //只能判断data=null,空字符串的话还是会走进let 1,所以判断字符串的话,还是尽量用TextUtils.isEmpty()来做判断                 
    var data: String? = ""
            data?.let {
                Log.e("gex"," 1: data $data")
            }?:let {
    
                Log.e("gex"," 2: data is null")
            }           
    

    Lambda表达式 setOnClickListener方法简洁

    audioPlaySpeed3.setOnClickListener { mPlayController?.setPlaySpeed(2.toFloat()) }
    

    实体Bean

    • data class 必须有构造参数
    @Parcelize
    data class CourseEntity(
            val c_code: String = "",
            val intro: String = "",
            var style: String = "",
            val img: String = "",
            val author: String = "",
            val free: String = "",// 0:免费 1:收费
            val duration: String = ""
    ) : Parcelable, MainEntity(), Serializable {
        var channelTags = ArrayList<ArrayList<TagEntity>>()
        fun isFree() = TextUtils.equals(free, "0")
    }
    
    • class 构造参数非必须有
    • 不需要增加get和set方法,属性直接调用
    • Parcelize序列化,build.gradle中添加如下,然后实体类打上注解@Parcelize,并实现Parcelable
    apply plugin: 'kotlin-android-extensions'
    

    范型T

    • Kotlin写法
    fun <T> createService(service: Class<T>): T {
            val retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            return retrofit.create(service)
        }
    
    • Java写法
    public <T> T createService(Class clazz) {
            Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(mOkHttpClient).addConverterFactory(CustomGsonConverterFactory.create()).build();
            return (T) retrofit.create(clazz);
        }
    

    循环

    var sb = StringBuilder()
    for ((k, v) in mParams) {
         sb.append("key: $k").append("--").append("value: $v")
    }
    

    String字符串拼接

    • 主要通过$符号来拼接
    var name="Gex"
    var age=30
    var m = "My name is $name , age is $age !"
    
    var user=User()
    var str="My name is ${user.name} , age is ${user.age} !"
    
    

    关键字

    • open: 允许其它类继承;kotlin类默认都是final,禁止继承
    • const: 声明编译期常量
    • lateinit: 延迟初始化,避免空检查,只能用在var类型
    • lazy{} 只能用在val类型
    val name: String by lazy { "Gex" }
    lateinit var adapter: MyAdapter
    

    FindViewById

    Activity和Fragment中

    tvName.text = notice.name
    tvNumber.text = ""
    ivIcon.setImageUrlAsync(icon, true)
    

    Adapter中的ViewHolder

       view.tvName.text = notice.name
       view.tvNumber.text = ""
       view.ivIcon.setImageUrlAsync(icon, true)
    

    未完待续...

    相关文章

      网友评论

        本文标题:Kotlin快速入门文档和习惯用法

        本文链接:https://www.haomeiwen.com/subject/yvdqqqtx.html