距离我上次写kotlin的代码已经过去了三个多月,前两天在写测试代码的时候,写了几个lambda表达式,回头发现这个跟kotlin的高阶函数还不一样,怎么写来着给忘了.果然是技术只要不使用,遗忘的速度让人吃惊.
kotlin新的东西其实很多,google的社区或者kotlin的中文站都有大量的细节知识,可以从头到尾了解学习.不过从java转到kotlin都是直接上手,一边写一遍查.
个人觉得google官方这份31天学习kotlin的文章,可以说详细而简单.demo简洁有力.
31 天,从浅到深轻松学习 Kotlin
下面是kotlin里边在项目中比较常用的东西,也是直接使用中感觉最便捷的地方.做个记录.
1.比java占位符更好用扩展的字符串拼接
var prefix = 1
var subfix = UserInfo("lily", "japan", 3, "no")
var str = "here is a user $prefix ${subfix.name}"//here is a user 1 lily
str = """ she is "${subfix.name}" """ // she is "lily"
2.空指针推断
//java
List mData = null;
public int getItemCount(){
return mData == null ? 0:mData.size();
}
//kotlin
var mData: List? = null
override fun getItemCount(): Int {
return mData?.size ?: 0
}
//java
String deptId = null;
if(LuckinBaseData.getInstance().getShopInfo()!=null &&
LuckinBaseData.getInstance().getShopInfo().deptInfo != null){
deptId = LuckinBaseData.getInstance().getShopInfo().deptInfo.deptId;
}
//kotlin
var deptId = LuckinBaseData.getInstance().getShopInfo()?.deptInfo?.deptId
3.方法的默认参数减少重载,这里最好的例子应该是View的四个构造方法
class SimpleAdapter(context: Context = BaseApplication.getInstance() , parent: RecyclerView) {
fun testM(var i = 1;var j = 2){
Log.d("test","${i+j}")
}
}
var simpleAdapter1 = SimpleAdapter(Activity.this,rv_content)
var simpleAdapter2 = SimpleAdapter(parent = rv_content)
simpleAdapter1.testM()//1+2 = 3
simpleAdapter1.testM(3,4)//3+ 4 = 7
simpleAdapter1.testM(5)//5+2 = 7
simpleAdapter1.testM(j = 6)//1+6 = 7
4.高阶函数的支持,不在需要通过接口进行行为(方法)的传递,方法可以像变量传递
class SimpleAdapter(context: Context , parent: RecyclerView) {
var onItemClick: ((Int) -> Unit)? = null
override fun onBindViewHolder(holder: SimpleViewHolder, pos: Int) {
//这里的代码有些臃肿以及不必要,我只是为了test demo
val userInfo = mData!![pos] as UserInfo
userInfo.apply {
holder.itemView.tv_info.text = "$id $name $address"
holder.itemView.setOnClickListener {
onItemClick?.run {
this(pos)
}
}
}
}
}
var simpleAdapter1 = SimpleAdapter(Activity.this,rv_content)
simpleAdapter1.onItemClick = {
Toast.makeText(baseContext, "click -- $it", Toast.LENGTH_SHORT).show()
}
5.通过插件扩展直接使用View的id在类文件中使用View对象
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_test)
tv_name.text = "tv_name无需声明直接使用"
}
override fun onBindViewHolder(holder: SimpleViewHolder, pos: Int) {
val userInfo = mData!![pos] as UserInfo
userInfo.apply {
holder.itemView.tv_info.text = "tv_info也可以不用findViewById"
holder.itemView.setOnClickListener {
onItemClick?.let {
it(pos)
}
}
}
}
kotlin的高阶函数
C语言的方法变量
Java8的Lambda表达式
Groovy的闭包.
以及母猪的产后护理.
我这个知识啊,都学杂了.