5

take a look at this simple extension function i have infix:

infix fun View.isValidColor(hexColor: String?): Boolean {
    var isValid = true
    return hexColor?.let {
        try {
            Color.parseColor(it)
        } catch (e: Throwable) {
            isValid = false
        }
        isValid
    } ?: false
}

//notice how i have infix the extension meaning brackets are not needed, hopefully making it easier to read.  

Now lets see the usage and what i have tried:

enter image description here

its not being infix and it follows the rule for infix that:

  1. Must be member functions or extension functions.
  2. They must have a single parameter.
  3. The parameter must not accept a variable number of arguments and must have no default value.

what am i doing wrong ?

UPDATE:
I ALSO tried this but its working by explicitly calling the referring class: enter image description here

since now im using the explicit object why did it fail ? ivLogo is a ImageView synthetic from kotlin.

Sergio
  • 27,326
  • 8
  • 128
  • 149
j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • `Note that infix functions always require both the receiver and the parameter to be specified. When you're calling a method on the current receiver using the infix notation, you need to use this explicitly; unlike regular method calls, it cannot be omitted. This is required to ensure unambiguous parsing.` - quote from the docs and also mentioned in your link – awesoon Apr 27 '19 at 04:54
  • i posted a update, so now i tried calling it with the view itself. should be similar to saying this.isValidColor "#fffff" right ? but it still fails. how would you go about this ? – j2emanue Apr 27 '19 at 05:12
  • There should not be a dot between object and the function – awesoon Apr 27 '19 at 05:13
  • Actually I am not sure if `isValidColor` is a good infix function. I would go with a plain function instead. – awesoon Apr 27 '19 at 05:14
  • its working now , thanks – j2emanue Apr 27 '19 at 05:29

1 Answers1

8

To make infix function work, to the left of it should be placed an actual instance of object:

val result = someView isValidColor "#FFFFFF"
Sergio
  • 27,326
  • 8
  • 128
  • 149