Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Android Studio/IntelliJ "Can be joined with assignment" Inspection Warning

I'm new to Koltin and really loving it so far, but I've hit a snag. I'm sure I'm missing something extremely, extremely basic here, but nonetheless, I'm a loss, and I appreciate any help.

I converted a simple java class to Kotlin using the Android Studio/IntelliJ command. After this conversion, I am getting an inspection warning that I'm unsure how to resolve. I had converted 15-20 classes (many of which were far more complicated) to Kotlin before this class, and have yet to see this warning.

enter image description here

Again, I know this must be something really basic. But I poured through the Kotlin docs on variables and classes and couldn't find anything related to 'assignment' or initializing multiple variables at once. Maybe I'm not understanding the terms in the message? I've also Googled the exact message string ("Can be joined with assignment") to no avail.

ImagePagerAdapter.kt

abstract class ImagePagerAdapter(protected var context: Context) : PagerAdapter() {
    protected var inflater: LayoutInflater
    protected var images: List<Uri>

    interface ImageLoadingListener {
        fun onLoadingComplete()
        fun onLoadingStarted()
    }

    init {
        this.inflater = LayoutInflater.from(context)
        this.images = emptyList()
    }

    override fun getCount(): Int {
        return images.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    fun bindImages(images: List<Uri>) {
        this.images = images
    }
}

Many thanks in advance!

like image 667
madcow Avatar asked Mar 04 '17 19:03

madcow


1 Answers

It's telling you that instead of having a separate init block, you could be initializing the variables at the place where you've declared them in the class, like so:

protected var inflater: LayoutInflater = LayoutInflater.from(context)
protected var images: List<Uri> = emptyList()

You should be getting the Alt+Enter intention action at the place of the warning to do this rewriting for you, like this:

Join declaration and assignment intention action

Additionally, in this form, you could clean the types up a bit like this:

protected var inflater = LayoutInflater.from(context)
protected var images = emptyList<Uri>()
like image 105
zsmb13 Avatar answered Oct 19 '22 11:10

zsmb13