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. 实现(implements)

java:

public class HomeBase implements Parcelable { }


kotlin:

class HomeBase() : Parcelable{}


注意:HomeBase后面跟的小括号即表示一个无参数的构造函数,参见上面说的的《声明构造方法》

5. 静态内部类

kotlin默认的内部类是静态内部类,不能持有外部类的状态(属性、方法等)
给内部类加上inner关键词之后,就会变成非静态内部类

class HomeAdapter{
        private inner class SpanSizeLookup : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return list[position].spanCount
            }
        }
}

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
        }

}

猜你喜欢

转载自www.cnblogs.com/Sharley/p/10481914.html