Kotlin学习

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

2018-11-21  本文已影响0人  GexYY

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的使用

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

@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")
}
apply plugin: 'kotlin-android-extensions'

范型T

fun <T> createService(service: Class<T>): T {
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        return retrofit.create(service)
    }
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} !"

关键字

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)

未完待续...

上一篇下一篇

猜你喜欢

热点阅读