1

I am starting to work with the Kotlin fun extensions. I've created some that are working correctly for me, but I have one with the ImageView context that doesn't work and I don't understand why.

The extension function is this:

fun ImageView.imageCardAssignation(imageSelected: Int): Int {

    when(imageSelected){
        0 -> R.drawable.card_amazon
        1 -> R.drawable. card_card
        2 -> R.drawable. card_house
    }
    return imageSelected
}

The idea is that depending on the number (Int) that you pass as a parameter, assign one image or another to the ImageView.

I invoke it as follows:

vb.selectImage.setImageResource (imageCardAssignation (0))

But the ID indicates the error:

- none of the following candidates is applicable because os receiver type mismatch

I think the context has to be ImageView

What am I doing wrong?

Thank you very much and greetings.

Sergio76
  • 3,835
  • 16
  • 61
  • 88
  • 2
    You're not using `imageCardAssignation` as an extension function. An extenstion function would've been called like `vb.selectImage.imageCardAssignation(0)` – Michael Apr 30 '20 at 18:19
  • I understand, but in this case, calling the extension function in the right way: vb.selectImage.imageCardAssignation (0) How would you apply the setImageResource? – Sergio76 Apr 30 '20 at 18:35
  • 1
    `vb.selectImage.setImageResource(vb.selectImage.imageCardAssignation (0))` or `vb.selectImage.run { setImageResource(imageCardAssignation(0)) }` – Tenfour04 Apr 30 '20 at 18:36
  • 1
    It would be cleaner to write an extension function that calls `setImageResource` for you. `fun ImageView.setImageIndex(index: Int) { setImageResource( when(index) { /* */ } ) }` The way you have the function now, it doesn't even need to be an extension because you don't use the ImageView argument for anything. Also, you need to move the `return` before the `when` because you are currently discarding the results of the `when` statement. And it needs an `else` branch. – Tenfour04 Apr 30 '20 at 18:41

1 Answers1

0

it should be something like this:

    fun ImageView.imageCardAssignation(imageSelected: Int): Int {

    return when(imageSelected){
        0 -> R.drawable.card_amazon
        1 -> R.drawable.card_card
        2 -> R.drawable.card_house
    }

}

i'm supposing that "R.drawable.card_amazon" is a Int, otherwise the return type will be wrong