简体   繁体   English

如何将此 Android Kotlin 代码转换为 Java 代码

[英]How to translate this Android Kotlin code to Java code

class MainAdapter : RecyclerView.Adapter<MainAdapter.ViewHolder>() {

    var list: List<Int> = arrayListOf()
    var tracker: SelectionTracker<Long>? = null

    init {
        setHasStableIds(true)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val number = list[position]
        tracker?.let {
            holder.bind(number, it.isSelected(position.toLong()))
        }
    }

I would like to understand this example.我想了解这个例子。 What does tracker?.let translate to? tracker?.let翻译成什么? And also what's the equivalent of init in Java?还有 Java 中init的等价物是什么?

I would recommend another way to read kotlin code assuming you are well familiar with java.假设您非常熟悉 java,我会推荐另一种阅读 kotlin 代码的方法。 You can use below option in android studio.您可以在 android studio 中使用以下选项。

解码kt文件

After this just click decompile and Voila!, you will get java code.之后只需单击反编译和瞧!,您将获得java代码。

字节码

So now you can read any kotlin code.所以现在你可以阅读任何 kotlin 代码。

init

As per documentation - init is equivalent to a constructor in java.根据文档 - init 相当于 java 中的构造函数。 here we can initialize a variable.在这里我们可以初始化一个变量。

let

As per documentation- Kotlin let is a scoping function wherein the variables declared inside the expression cannot be used outside.根据文档 - Kotlin let是一个作用域函数,其中在表达式内部声明的变量不能在外部使用。

tracker?.let {
    holder.bind(number, it.isSelected(position.toLong()))
}

here it is a copy of tracker.changing it will not affect on tracker variable.是跟踪器的副本。更改不会影响跟踪器变量。

MainAdapter equivalent in Java code is something like that: Java 代码中的 MainAdapter 等价物是这样的:

class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {

    List<Integer> list = new ArrayList<>();
    SelectionTracker<Long> tracker;

    public MainAdapter() {
        setHasStableIds(true);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        int number = list.get(position);

        if (tracker != null) {
            holder.bind(number, tracker.isSelected(position.toLong()));
        }
    }
}
class M {
    var age: Int = 0
}
fun main(){
    val m = M()
    m.let {
        it.age = 11
     }
    println(m.age)
}

above output "11", so "let" doesn't copy the receiver, "it" is just point to the receiver, it has side-effect在输出“11”上方,所以“let”不会复制接收器,“it”只是指向接收器,它有副作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM