Kotlin学习_Kotlin插件安装

什么是Kotlin?

Kotlin是针对JVM、Android 和浏览器的静态编程语言!
100% 与 Java™ 可互操作!

Kotlin在Android上的使用

Kotlin可以直接将布局的id来当成变量使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is TitleHolder) {
// 分类
holder.itemView.new_item_title.text = mDatas?.get(position)?.type
} else if (holder is ContentViewHolder) {
with(holder.itemView) {
// 名称
new_item_text.text = mDatas?.get(position)?.desc
// 作者
new_item_user.text = mDatas?.get(position)?.who.let { Constant.NEW_ITEM_USER_NULL }
}
// 点击
holder.itemView?.setOnClickListener {
onClick ->
val intent = Intent(mContext, DetailActivity::class.java)
val data = Bundle()
data.putString(Constant.URL, mDatas?.get(position)?.url)
intent.putExtras(data)
mContext?.startActivity(intent)
}
}
}

Java在写Bean类的时候是这样写的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

public class DataTypeBean {

private boolean error;
private List<ResultsBean> results;

public boolean isError() {
return error;
}

public void setError(boolean error) {
this.error = error;
}

public List<ResultsBean> getResults() {
return results;
}

public void setResults(List<ResultsBean> results) {
this.results = results;
}

public static class ResultsBean { ... }
}

而在Kotlin中直接用数据类(Data Classes)写

1
2
3
4
5
6
7
8
9
// DataTypeBean类
data class DataTypeBean(var error: Boolean = false, var results: MutableList<ResultsBean>? = null)

// ResultsBean类
data class ResultsBean(var _id: String? = null, var createdAt: String? = null,
var desc: String? = null, var publishedAt: String? = null,
var source: String? = null, var type: String? = null,
var url: String? = null, var used: Boolean = false,
var who: String? = null, var images: MutableList<String>? = null)

是不是很方便,很简洁,下面就介绍如何安装Kotlin插件

Kotlin的插件安装

Settings->Plugins->Browse Repositories->搜索Kotlin

安装Kotlin插件

项目添加Kotlin(Android Studio)

已存在的项目直接转换为Kotlin

Code->Convert Java file to Kotlin file

  1. 转换完成后,会要求配置Kotlin
    kotlin_not_configured
  2. 选择Modules和Kotlin的版本
    kotlin_configure
  3. Sync Gradle
    sync_gradle
  4. 转换后的文件,会有些语法之类的错误,这个后面再说

新建项目

  1. Project的gradle

    • buildscript里面添加kotlin的版本,当前是1.0.4

      1
      ext.kotlin_version = '1.0.4'
    • dependencies里面添加Kotlin依赖

      1
      classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  2. Module的gradle

    • 添加apply plugin

      1
      2
      apply plugin: 'kotlin-android'
      apply plugin: 'kotlin-android-extensions'
    • dependencies添加依赖

      1
      2
      compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
      compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
  3. 运行app