"Useless" member extensions

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 
}

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

1 Like

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

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

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.