kotlin语法使用笔记
kotlin中文文档:http://www.kotlindoc.cn/ClassesAndObjects/Classes-and-Inheritance.html
1. 声明类的构造方法
例如继承FragmentPagerAdapter时声明一个构造方法——
class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
init {
//初始化
}
}
当声明多个构造方法时,如
public class LoadMoreRecyclerView extends RecyclerView {
public LoadMoreRecyclerView(Context context) {
super(context);
}
public LoadMoreRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LoadMoreRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
写作kotlin时,将主构造函数写在类名后(函数类不使用初始化时可将大括号去掉):
class LoadMoreRecyclerView(context: Context?) : RecyclerView(context) {
constructor(context: Context, attrs: AttributeSet):this(context){
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int):this(context, attrs)
}
如果是一个实体类,需要实现自定义的构造方法:
constructor(id: Long, price: Double, url: String): this() {
this.id = id
this.price = price
this.url = url
}
2. 静态方法
定义静态方法时用companion object{}包裹在方法外层
3. 定义一个常量不为空时,使用!!和?.的区别:
①!!
a!!.foo()
//相当于java:
if(a!=null){
a.foo();
}else{
throw new KotlinNullPointException();
}
②?.
a?.foo()
//相当于java:
if(a!=null){
a.foo();
}
4. 继承(extend)和实现(implements)
1.继承:
java——
public class MainActivity extends BaseActivity{}
kotlin——
class MainActivity : BaseActivity(){}
2.实现:
java——
public class HomeBase implements Parcelable { }
kotlin——
class HomeBase() : Parcelable{}
注意:HomeBase后面跟的小括号即表示一个无参数的构造函数,参见上面说的的《声明构造方法》
3.同时继承且实现,逗号隔开就行了:
java——
public class MainActivity extends BaseActivity implements MainContract.View {}
kotlin——
class MainActivity : BaseActivity(), MainContract.View {}
5. 静态内部类
kotlin默认的内部类是静态内部类,不能持有外部类的状态(属性、方法等)
给内部类加上inner关键词之后,就会变成非静态内部类
class HomeAdapter{
private inner class SpanSizeLookup : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return list[position].spanCount
}
}
}
在非静态的方法中调用时,需要加上open,即
open inner class SpanSizeLookup : GridLayoutManager.SpanSizeLookup() {
}
6. return的使用
当直接返回到方法外时
fun method{
if (isInEditMode) lit@{
return@lit
}
}
7. 特殊语法
url == null ? "" : url 可写作 url ?: ""
holder instanceof HeadHolder 可写作 holder is HeadHolder
在new一个变量并调用其实现方法时(类似注册监听)
MarqueeLayoutAdapter<HomeBase> topAdapter = new MarqueeLayoutAdapter<HomeBase>(headlineList) {
@Override
protected void initView(View view, int position, HomeBase item) {
((TextView) view).setText(item.getName());
}
};
可写作
val topAdapter = object : MarqueeLayoutAdapter<HomeBase>(headlineList) {
override fun initView(view: View, position: Int, item: HomeBase) {
(view as TextView).text = item.name
}
}
8. 修饰符(public,private,protected,internal )
kotlin中同样有修饰符,与java同样的public,private,protected,kotlin中默认为public,所以可以省略不写,还有一个java中没有的interval修饰符
internal 修饰类的方法,表示这个类方法只适合当前module使用,如果其他module使用的话,会找不到这个internal方法或者报错
比如在moduleA中创建方法methodA B:
class Activity_A() {
fun methodA(){
Log.i("debug=","methodA")
}
internal fun methodB(){
Log.i("debug=","methodB")
}
}
然后在moduleB中调用:
void callMethod(){
new Activity_A().methodA(); //正常。
new Activity_A().methodB();//报错,usage of kotlin internal declaration from different module
}
9. BaseFragment<T>的使用
一般都会有一个fragment的基类,如:
abstract class BaseFragment<T : BasePresenter> : Fragment(){
...
}
当在java中的使用如下时:
private ArrayList<BaseFragment> fragments;
在kotlin中的用法照理(对,照我的理)来说是这样:
val tabs = ArrayList<BaseFragment>()
但是会报错
One type argument expected for class BaseFragment<T : BasePresenter> : Fragment
提示需要匹配基类的参数类型,即val tabs = ArrayList<BaseFragment<SomePresenterType>>()
val tabs = ArrayList<BaseFragment<BasePresenter>>()
而BasePresenter如果还有继承,如
interface BasePresenter<T : BaseView> {}
那么就得再加上basePresenter的参数类型:
val tabs = ArrayList<BaseFragment<BasePresenter<BaseView>>>()
10. 取消findViewById
在kotlin中已经不再使用findViewById了,而是直接使用控件的id名:
java中:
mTextView = view.findViewById(R.id.textl_view);
mTextView.setText("Shirley");
kotlin:
textl_view.text = "Shirley"
11. switch & when
这里就直接上代码吧
java:
switch (currentState) {
case NORMAL_STATE:
if (mNormalView == null) {
return;
}
mNormalView.setVisibility(View.INVISIBLE);
break;
case ERROR_STATE:
mErrorView.setVisibility(View.GONE);
default:
break;
}
kotlin:
when (currentState) {
NORMAL_STATE -> {
if (mNormalView == null) {
return
}
mNormalView.visibility = View.INVISIBLE
}
ERROR_STATE -> mErrorView.visibility = View.GONE
else -> {
}
}
12. xx.class的表达
java:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
kotlin:
val intent = Intent(this, AboutActivity::class.java)
startActivity(intent)
13.获取实体类的get/set方法
kotlin的bean类不用写get/set方法,那么当要调用该方法的时候怎么使用呢
假设实体类为User
class User {
var code: Int =
var desc: String? = null
var tid: String? = null
var data: DataBean? = null
}
当要获取 getData() 的时候,直接取 userBean.data ,注意当获取data后的数据,比如 getData().getName() 时,要做data的非空判断:userBean.data?.name
而当要 setData() 时,写作 userBean.data = xx; 即可
14.文件读取
在kotlin中使用输入输出流读写文件时,如果照Java写法
while ((len = inStream.read(buf)) != -) {
fos.write(buf, , len);
}
则会报错Assignments are not expressions,and only expressions are allowed in this context
kotlin应写作
do {
len = inStream.read(buf)
if (len != -) {
fos.write(buf, , len)
}
} while (true)
15.Array与List互转
Java:
list --->array
List<String> l = new ArrayList<>();
String[] s = l.toArray(new String[]);
array ---> list
String[] arr = new String[];
List<String> list = Arrays.asList(arr);
kotlin:
list --->array
val list = ArrayList<String>()
val arr = a.toTypedArray()
array ---> list
val l = arrayOfNulls<String>()//String[] s = new String[1]
val list = Arrays.asList<String>(*arr)
需要注意的是分割字符串的话,Java是直接转数组,kotlin中是转list,需要toTypedArray()后转数组
Java:
String str = "早,上,好";
String[] msg = str.split(",");
kotlin:
String str = "早,上,好";
val msg = str.split(",").toTypedArray()
也就是说 分割字符串转list,kotlin只需要 val list= str.split(",") 即可
kotlin语法使用笔记的更多相关文章
- 五分钟学会 Kotlin 语法
为什么使用Kotlin 项目一期在收尾了终于有时间折腾了,一个多月以来Kotlin从入门到现在,坚持用来开发的切身感受.因为语法与Java的区别挺大的一开始很想放弃,如果不是因为项目在使用,想必很少人 ...
- Golang 语法学习笔记
Golang 语法学习笔记 包.变量和函数. 包 每个 Go 程序都是由包组成的. 程序运行的入口是包 main. 包名与导入路径的最后一个目录一致."math/rand" 包由 ...
- MarkDown语法 学习笔记 效果源码对照
MarkDown基本语法学习笔记 Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式. 下面将对Markdown的基本使用做一个介绍 目 ...
- 毕业设计 之 五 PHP语法学习笔记
毕业设计 之 四 PHP语法学习笔记 作者:20135216 平台:windows10 软件:XAMPP,DreamWeaver 说明:该笔记是对网站编程语言的详细学习 一.PHP基础 0. 关于环境 ...
- JavaScript基础——JavaScript语法基础(笔记)
JavaScript语法基础(笔记) 1.语言编码 JavaScript语言建立在Unicode字符集基础之上,因此脚本中,用户可以使用双字节的字符命名常量.变量或函数等. [示例] var 我=&q ...
- doy05循环语法学习笔记
doy05循环语法学习笔记 一.while循环语法: 1.基本用法示例 x = 1 while x <= 5: print(x) x += 1 2.死循环:永远不结束的循环 如:while Tr ...
- Kotlin语法(函数和lambda表达式)
三.函数和lambda表达式 1. 函数声明 fun double(x: Int): Int { } 函数参数是用 Pascal 符号定义的 name:type.参数之间用逗号隔开,每个参数必须指明类 ...
- Mustache.js语法学习笔记
原文地址:http://www.cnblogs.com/flypig88/archive/2012/05/14/2497780.html 看了Mustache的github,学学其中的语法,做个笔记 ...
- Kotlin入门学习笔记
前言 本文适合人群 有一定的java基础 变量与方法 变量声明及赋值 var 变量名: 变量类型 val 变量名: 变量类型 这里,var表示可以改变的变量,val则是不可改变的变量(第一个赋值之后, ...
随机推荐
- Java笔记(十五) 并发包
并发包 Java中还有一套并发工具包,位于包java.util.concurrent下,里面包括很多易用 且很多高性能的并发开发工具. 一.原子变量和CAS 为什么需要原子变量,因为对于例如count ...
- jquery 1.7.2源码解析(二)构造jquery对象
构造jquery对象 jQuery对象是一个类数组对象. 一)构造函数jQuery() 构造函数的7种用法: 1.jQuery(selector [, context ]) 传入字符串参数:检查该字符 ...
- U盘安装Ubuntu 14.04 LTS
1.下载Ubuntu14.04 LTS 从Ubuntu官网下载->http://releases.ubuntu.com/14.04/ 2.将Ubuntu14.04安装到U盘 下载U盘系统安装工具 ...
- vue事件对象、冒泡、阻止默认行为
事件对象: <input type="button" name="" value="按钮" @click="show($ev ...
- sql 索引笔记
以下资料来自MSDN. 数据库注意事项 设计索引时,应考虑以下数据库准则: 一个表如果建有大量索引会影响 INSERT.UPDATE 和 DELETE 语句的性能,因为在表中的数据更改时,所有索引都须 ...
- hihocoder1051 补提交卡(贪心)
http://hihocoder.com/problemset/problem/1051 一开始dfs暴搜超时 这题关键在于理解到,肯定是补连续的几天.所以说写贪心之前要好好想想,怎么贪. //补题卡 ...
- [转]开源.net 混淆器ConfuserEx介绍
今天给大家介绍一个开源.net混淆器——ConfuserEx http://yck1509.github.io/ConfuserEx/ 由于项目中要用到.net 混淆器,网上搜寻了很多款,比如Dotf ...
- Linux内存管理学习资料
下面是Linux内存管理学习的一些资料. 博客 mlock() and mlockall() system calls. All about Linux swap space 逆向映射的演进 Linu ...
- Column 'u_id' in field list is ambiguous
- mac下svn提交失败的解决方法
$svn ci maps.xml然后出现一个文件svn-commit.4.tmp,在文件svn-commit.4.tmp中有如下内容: --This line, and those below, ...