How to set an adapter in a fragment in Kotlin? [duplicate]

I want to set a carusel adapter in a fragment. I use in XML

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="190dp"
        android:layout_marginBottom="8dp"/>

and in Kotlin:

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    val viewPagerAdapter = ViewPagerAdapter(activity)
    viewPager!!.adapter = viewPagerAdapter

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_login, container, false)
}

Unfortunately I get

kotlin.KotlinNullPointerException

for

viewPager!!.adapter = viewPagerAdapter 

line. If I use the same code in the activity main (no fragment) it works perfectly. I would be grateful for any ideas how I could fix this!

Source: Android Studio Questions

LEAVE A COMMENT