0

"Smart cast to "GridLayoutManager" is impossible, because 'ViewManager' is a mutable property that could have changed by this time"

is the Error that AndroidStudio shows when trying to add a Divider to my RecyclerView.

PixelsFragment.kt

class PixelsFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var viewManager: RecyclerView.LayoutManager
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private var listener: OnFragmentInteractionListener? = null
    private lateinit var pixels: List<Pixel>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        var numberOfColumns = 1

        viewManager = GridLayoutManager(this.context, numberOfColumns)
        viewAdapter = MyRecyclerViewAdapter(pixels)


        recyclerView = view!!.findViewById<RecyclerView>(R.id.RVJanuary).apply {
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
            addItemDecoration(DividerItemDecoration(recyclerView.context, viewManager.getOrientation())) //Error on this line, underlining viewManager
        }


    }
}

I found this answer which says that such a problem can be caused because the variable could happen to be null by the time that the line is executed, and then they provide 3 solutions. However, to my understanding, viewManager can by no means be null since I declared it as non-nullable variable. Therefore, I am looking for a different explanation and solution.

S. Czop
  • 602
  • 1
  • 6
  • 17

1 Answers1

5

You've declare viewManager as a RecyclerView.LayoutManager. The generic RecyclerView.LayoutManager does not have a getOrientation() method - that method only exists on LinearLayoutManager and its subclasses, such as the GridLayoutManager that you are using.

What the error message is telling you is that it cannot assume that the viewManager of type RecyclerView.LayoutManager is a GridLayoutManager since it is a mutable property - you could have set it to some other LayoutManager that does not have a getOrientation() method.

The easiest way to solve this is to change the type of your viewManager to GridLayoutManager. That way, only a GridLayoutManager would be available and getOrientation() is guaranteed to be available.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443