Tips:在AndroidStudio的Java文件中編寫一段代碼想际,然后將其粘貼到kt文件中,它會自動轉(zhuǎn)換為Kotlin
基本數(shù)據(jù)類型
Kotlin 的基本數(shù)值類型包括 Byte怀估、Short狮鸭、Int、Long多搀、Float歧蕉、Double 等。不同于Java的是康铭,字符不屬于數(shù)值類型惯退,是一個獨立的數(shù)據(jù)類型。
類修飾符
// 屬性修飾符
annotation //注解類
abstract //抽象類
final //類不可繼承从藤,默認(rèn)屬性
enum //枚舉類
open //類可繼承催跪,類默認(rèn)是final的
// 訪問權(quán)限修飾符
private //僅在同一個文件中可見
protected //同一個文件中或子類可見
public //所有調(diào)用的地方都可見
internal //同一個模塊中可見
//注:新建的類默認(rèn)是final的,想要被繼承需要加open修飾符
類的構(gòu)造器
class Person(name : String呛哟, age : int) {
}
翻譯成java為:
final public class Person {
public Person(String name, int age){
}
}
//kotlin默認(rèn)生成一個帶參的構(gòu)造函數(shù)叠荠,kotlin中的類定義同時也是構(gòu)造函數(shù),kotlin增加了一個新的關(guān)鍵字init用來處理類的初始化問題扫责,init模塊中的內(nèi)容可以直接使用構(gòu)造函數(shù)的參數(shù)
class Person(name : String榛鼎, age : int){
init{
// to do something
}
}
//kotlin中如何實現(xiàn)不同參數(shù)的構(gòu)造函數(shù)
//提供了次級構(gòu)造函數(shù),次級構(gòu)造函數(shù)用constructor加上參數(shù),后面用this加上主構(gòu)造函數(shù)的參數(shù)者娱。同時次級構(gòu)造函數(shù)中可以直接進(jìn)行代碼操作
class CustomView :TextView{
constructor(context: Context?) : this(context,null)
constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs,0)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
}
Android 中的使用
View的操作
var textview:TextView? = null
textview = findViewById(R.id.tv) as TextView
textview.setOnClickListener{
toast("Hello world!")
}
// 注:
// 抡笼?:表示當(dāng)前是否對象可以為空
// !;器ⅰ: 表示當(dāng)前對象不為空的情況下執(zhí)行推姻,為空則拋出空指針異常
接口中的回調(diào)寫法
weather.enqueue(object :Callback<String>{
override fun onFailure(call: Call<String>?, t: Throwable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onResponse(call: Call<String>?, response: Response<String>?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
mBack.setOnClickListener(
object : View.OnClickListener {
override fun onClick(v: View) {
finish()
}
})
靜態(tài)方法
//伴生對象的初始化是在類加載的時候,與java的靜態(tài)初始化器相對應(yīng)
companion object{
//這里寫方法
}
//注:一個類只能有一個伴生對象
單例寫法
//類似java的靜態(tài)內(nèi)部類實現(xiàn)單例模式
class WeatherManager private constructor(){
companion object {
fun get():WeatherManager{
return Holder.instance
}
}
private object Holder{
val instance = WeatherManager()
}
}
接口定義
interface MyInterface {
fun bar() // 未實現(xiàn)
}
繼承和實現(xiàn)
class Man : Person(){
}
擴(kuò)展函數(shù)
//我們可以在不改變源碼的情況下框沟,為源碼新增一個我們需要的方法
// 擴(kuò)展函數(shù) swap,調(diào)換不同位置的值
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // this 對應(yīng)該列表
this[index1] = this[index2]
this[index2] = tmp
}
fun main(args: Array<String>) {
val l = mutableListOf(1, 2, 3)
// 位置 0 和 2 的值做了互換
l.swap(0, 2) // 'swap()' 函數(shù)內(nèi)的 'this' 將指向 'l' 的值
println(l.toString())
}
when 表達(dá)式
//kotlin中沒有switch case表達(dá)式藏古,但是提供了一個when表達(dá)式
//switch-case
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_SUCCESS:
break;
case FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_FAILED:
break;
case FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_SUCCESS_EMPTY:
break;
default:
break;
}
return super.handleMessage(msg);
}
//when
fun handleMessage(msg: Message): Boolean {
when (msg.what) {
FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_SUCCESS -> {
}
FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_FAILED -> {
}
FeedbackInfoLogic.MSG_FEEDBACK_INFO_REQUEST_SUCCESS_EMPTY -> {
}
else -> {
}
}
return super.handleMessage(msg)
}
//else相當(dāng)于default
POJO類
//傳統(tǒng)的java POJO類會要求寫一系列的模板代碼
public class User{
private long id;
private String name;
private String url;
private String mbid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMbid() {
return mbid;
}
public void setMbid(String mbid) {
this.mbid = mbid;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", url='" + url + '\'' +
", mbid='" + mbid + '\'' +
'}';
}
}
//而在kotlin中可以這樣寫
//使用關(guān)鍵字data會自動生成相應(yīng)的 equals、hashcode忍燥、toString 方法
data class User(
var id: Long,
var name: String,
var url: String,
var mbid: String)
//或
class User{
var id:Long? = null
var name:String? = null
var url:String? = null
var mbid:String? = null
}
Elvis操作符
// 使用Elvis操作符來給定一個在是null的情況下的替代值拧晕,當(dāng)user為null時name = empty
val name = user?.name ?: "empty"
let操作符
// let 操作符:如果對象的值不為空,則允許執(zhí)行這個方法梅垄。
//Java
if (user != null) {
text.setText(currentUser.name)
}
//Kotlin
user?.let {
println(it.name)
}
//it代表user這個對象
with 函數(shù)
//with 是一個非常有用的函數(shù)厂捞,它包含在 Kotlin 的標(biāo)準(zhǔn)庫中。它接收一個對象和一個擴(kuò)展函數(shù)作為它的參數(shù)队丝,然后使這個對象擴(kuò)展這個函數(shù)靡馁。這表示所有我們在括號中編寫的代碼都是作為對象(第一個參數(shù)) 的一個擴(kuò)展函數(shù),我們可以就像作為 this 一樣使用所有它的 public 方法和屬性机久。當(dāng)我們針對同一個對象做很多操作的時候這個非常有利于簡化代碼臭墨。
with(helloWorldTextView) {
text = "Hello World!"
visibility = View.VISIBLE
}
常用集合
List
A generic ordered collection of elements. Methods in this interface support only read-only access to the list
(一個有序的集合,僅支持對list的讀吞加,不支持寫)
MutableList
A generic ordered collection of elements that supports adding and removing elements.(支持添加和移除元素的有序集合)
Set
A generic unordered collection of elements that does not support duplicate elements.
Methods in this interface support only read-only access to the set;(不支持修改的無序的裙犹、不允許有重復(fù)元素的集合)
MutableSet
A generic unordered collection of elements that does not support duplicate elements, and supports
adding and removing elements.(支持添加和移除元素的無序的、不允許有重復(fù)元素的集合)
字符串相關(guān)
模板字符串
//使用$符號,避免字符串的拼接
val a = "android"
val name = "$a length is ${a.length}"
//name = android lenght is 7
原始字符串
//使用""" """包圍的字符串會保留原格式
val str = """
|java
|kotlin
|scala
|python
"""
列表遍歷
//可以使用如下代碼使用下標(biāo)來遍歷數(shù)組
for(i in list.indices){
println(list[i])
}
//使用迭代器遍歷
val iterator = list.iterator()
while (iterator.hasNext()){
println(iterator.next())
}
//使用forEach遍歷,算是kotlin中的一個語法糖
list.forEach {
println(it)
}
Kotlin內(nèi)存優(yōu)化
//使用懶加載衔憨,懶加載更有效率的利用內(nèi)存叶圃,因為我們只需要調(diào)用資源才能將資源加載到內(nèi)存中
val weatherService: WeatherService by lazy {
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(MoshiConverterFactory.create())
.build()
retrofit.create(WeatherService::class.java)
}
//在調(diào)用weatherService的情況下才初始化weatherService,可以優(yōu)化內(nèi)存
面向?qū)ο?/h3>
object類
//實現(xiàn)類似java中工具類可以使用object
object FileUtils {
fun getFiles(){
println("this is files")
}
}
//調(diào)用方法
FileUtils.getFiles()
一些學(xué)習(xí)網(wǎng)站
//實現(xiàn)類似java中工具類可以使用object
object FileUtils {
fun getFiles(){
println("this is files")
}
}
//調(diào)用方法
FileUtils.getFiles()
From Java to Kotlin:列出了許多 Java 與 Kotlin 對比的例子