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)

 

转载于:https://www.cnblogs.com/Sharley/p/10481914.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值