jat*_*ing 5 java static abstract-class kotlin companion-object
我从名为 UserViewHolder 的官方示例中学习了 ViewHolder 的使用。
public class UserViewHolder extends RecyclerView.ViewHolder {
static UserViewHolder create(LayoutInflater inflater, ViewGroup parent) {
UserItemBinding binding = UserItemBinding
.inflate(inflater, parent, false);
return new UserViewHolder(binding);
}
private UserItemBinding mBinding;
private UserViewHolder(UserItemBinding binding) {
super(binding.getRoot());
mBinding = binding;
}
public void bindTo(User user) {
mBinding.setUser(user);
mBinding.executePendingBindings();
}
}
Run Code Online (Sandbox Code Playgroud)
我要写很多ViewHolder类,所以我希望我能写一个抽象类。在 Java 中,它看起来像:
public abstract static class BaseViewHolder {
abstract static BaseViewHolder create()
abstract void bindTo()
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用 Kotlin 编写它,但最后我发现它不像在 Java 中那么简单。
abstract class BaseViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
abstract fun bindTo(viewModel: BaseViewModel)
}
Run Code Online (Sandbox Code Playgroud)
在 Kotlin 中,如果我想要一个静态函数,我需要在“伴随对象”中编写该函数。但它不能是一个“抽象”。
在 Java 中,带有抽象类的抽象类是常见的。
但是我如何在 Kotlin 中编写它呢?
更新:
我已经写了我自己的SleepViewHolder。我要写很多ViewHolder,比如AppleViewHolder,BananaViewHolder等等。所以我想构建一个BaseViewHolder作为模式。我的问题是,在这种情况下,编写模式BaseViewHolder的最佳方法是什么?我应该更改它的构造函数,还是公开创建函数?
open class SleepViewHolder private constructor(private val binding: ItemSleepBinding)
: RecyclerView.ViewHolder(binding.root) {
companion object {
@JvmStatic
fun create(inflater: LayoutInflater, parent: ViewGroup): SleepViewHolder {
val binding: ItemSleepBinding
= DataBindingUtil.inflate(inflater, R.layout.fragment_base, parent, false)
return SleepViewHolder(binding)
}
}
open fun bindTo(viewmodel: SleepViewModel) {
binding.vm = viewmodel
binding.executePendingBindings()
}
Run Code Online (Sandbox Code Playgroud)
}
在 中Kotlin,Java or C#,与类不同的是没有静态方法。在大多数情况下,建议简单地使用包级函数。
如果您需要编写一个无需类实例即可调用但需要访问类内部(例如工厂方法)的函数,则可以将其编写为该类内部对象声明的成员。
更具体地说,如果您在类中声明一个伴生对象,您将能够使用与在 中调用静态方法相同的语法来调用其成员Java/C#,仅使用类名作为限定符。
这是编写同伴类的方法
class MyClass {
companion object { } // will be called "Companion"
}
fun MyClass.Companion.foo() { // ...
}
Run Code Online (Sandbox Code Playgroud)
这就是你调用 foo() 函数的方式......
MyClass.foo()
Run Code Online (Sandbox Code Playgroud)