"Useless" member extensions


#1

I can define member extensions like this, but is there a way to use it?

interface Section<T> {
    fun matches(item: T): Boolean
}

class MyList<T>{
    val items: List<T> = listOf()
    
    val Section<T>.firstMatch: Int
        get() = items.indexOfFirst { this.matches(it) }
}

fun myMethod() {
    val myList = MyList<String>()
        
    val section = object : Section<String> {
        override fun matches(item: String): Boolean = 
            item == "something"
    }
 
    
    /* ??? */
    val x = section.firstMatch 
}

#2

val x = with(myList) { section.firstMatch }


#3

Thank you, that wasn’t obvious to me from the documentation.


#4

And is there a way to write that extension function in Section so that MyList doesn’t need to know about it?


#5

The reason for this kind of extension function (that effectively takes 2 this pointers) is to access both. You could of course reverse it and put it in Section instead. In some cases you need to use the this@... syntax though.