javaandroidkotlinstatickotlin-companion

Is it possible to extends a class that has a non empty constructor with a companion object


I have a code in Java that i want to change to Kotlin syntax. The jave code is:

  public class CountryDataItem (String countryNane,String countryUrl)
{
    public static RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent)
    {
        new ViewHolder (parent);
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        private TextView countryTextView;
        private ImageView countryImageView;
     
        public ViewHolder(@NonNull View view)
        {
            super(view);
            view.findViewById...
            ...
        }
    } 
}

Code is related to RecyclerView. I want to be able to create as many as ViewHolder's as i want from the static nested class type. I wrote the following code, but it feels me like a bad code, unreadable (I prefer not to write anonymous class but didn't know how to write the "static" ViewHolder Class and also always return the same field.

Code I have wrote:

   class CountryDataItem (val countryName :String, var countryFlagUrl )
{
    companion object
    {

         fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
             return object : RecyclerView.ViewHolder(parent) {
                 val countryNameTextView: TextView = parent.findViewById(R.id.country_name_tv)
                 val countryFlagUrl: ImageView = parent.findViewById(R.id.country_iv)
             }
         }
    }

I prefer to write a code with a companion object that extends RecyclerView.ViewHolder class buy since writing:

object ViewHolder: RecyclewView.ViewHolder enforce me the provide () and argument of type View to RecyclewView.ViewHolder

i can't do it


Solution

  • Nested classes are static by default in Kotlin. You have to mark them inner to make them not static. So your Java class could be like this in Kotlin:

    class CountryDataItem (val countryName: String, var countryFlagUrl: String) {
    
        companion object {
            fun onCreateViewHolder(parent: ViewGroup) = ViewHolder(parent)
        }
    
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val countryTextView: TextView = view.findViewById...
            val countryImageView: ImageView = view.findViewById...
        } 
    }