概述
最近已被Kotlin刷屏,那么kotlin到底是什么呢?Kotlin是一个基于JVM静态类型编程语言。它的主要优点目前我觉得有三点:简洁、简洁、简洁!让你用更少的代码获得更多的功能。
- Kotlin支持类型推断
- 用var表示变量,val表示常量
- 方法直接就fun
- 类的继承和实现更加简单化,使用:就哦了
- Kotlin不再让你再去写无聊的分号了
- etc ……
使用
Android studio中的使用方式,Eclipse请放弃治疗……
1.首先装Kotlin的插件
File>settings>Plugins
2.插件装完重启AS之后新建项目
也可以
3.配置
基本上as会帮我配置上,我们只需要加上
apply plugin: 'kotlin-android-extensions'
4.简单使用
第一点它的简洁在于不用findid,也不需要用注解,类也不需要实例化
不知道为什么他不会自动导包,所以无法找到布局下的id,所以需手动导包
import kotlinx.android.synthetic.main.xmlName.*
然后就放肆吧……
package com.example.kotlin
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main2.*
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
tv.text = "我是吴唐人"
tv.textSize = 20f
}
}
Example
下面是我的工具类
package com.example.kotlin
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
/**
* 作者:Tangren_ on 2017/5/13 17:56.
* 邮箱:wu_tangren@163.com
* TODO:一句话描述
*/
object Utils {
private val decimalFormat = DecimalFormat("######0.00")
private val sdf = SimpleDateFormat("yyyyMMddHHmmss")
private val sdf2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
/**
* 订单号
* @return
*/
fun OrderNo(): String {
val date = Date()
val builder = StringBuilder("gas")
builder.append(sdf.format(date))
return builder.append(buildRandom(3)).toString()
}
private fun buildRandom(length: Int): Int {
var num = 1
var random = Math.random()
if (random < 0.1)
random = random + 0.1
for (i in 0..length - 1) {
num = num * 10
}
return (random * num).toInt()
}
// 当前系统时间
val date: String
get() {
val format = SimpleDateFormat("yyyy-MM-dd")
val date = Date()
val dateString = format.format(date)
return dateString
}
fun payType(type: String): String {
if (type == "scan")
return "移动支付"
else if (type == "cash")
return "现金支付"
else if (type == "card")
return "会员支付"
else if (type == "1")
return "微信支付"
else if (type == "2")
return "支付宝"
else if (type == "3")
return "QQ钱包"
return "UNKNOW"
}
/**
* 元2分
* @param amount
* *
* @return
*/
fun Yuan2Fen(amount: String): String {
val f = java.lang.Float.valueOf(amount)!! * 100
return decimalFormat.format(f.toDouble())
}
/**
* 支付状态
* @param state
* *
* @return
*/
fun payState(state: String) = when (state) {
"0" -> "支付中"
"1" -> "支付成功"
"2" -> "支付失败"
"3" -> "已冲正"
"4" -> "已退款"
"5" -> "退款"
else -> "未知"
}
fun getPayType(t: String): String =
when (t) {
"微信" -> "1"
"QQ" -> "2"
else -> "3"
}
}
总结
既然Google已经承认了它,说明kotlin的优势还是有的,当然Java也不会被取代的,也不用非要做出取舍因为Kotlin 100%兼容Java,学习Kotlin有一个非常大的技巧就是通过Java转成Kotlin那么将会事半功倍,加油!