Super.method() calls overriden method in the same class?

class UpperCaseWriter(
    realWriter: Writer
) : FilterWriter(realWriter) {

override fun write(cbuf: CharArray, off: Int, len: Int) {
    val newBuff = CharArray(len)
    cbuf.copyInto(newBuff, destinationOffset = 0, startIndex = off, endIndex = off + len)
    newBuff.indices.forEach { n ->
        newBuff[n] = newBuff[n].uppercaseChar()
    }

    super.write(newBuff) // This should call FilterWriter's write method
}//but it seems it calls the 
below write() function that takes str 
not chararray

override fun write(str: String, off: Int, len: Int) {
    super.write(str.uppercase(), off, len) // but this is with different signiture
}
}

I am sorry for this basic question.
Is it because of delegation to realwriter(except for overriden methods), if so why super.?

Can you reproduce your problem on https://play.kotlinlang.org/? There’s a lot of code missing from your example, so it’s hard to know what is going on.

2 Likes

I agree, we need a reproducible example. Most probably your observation is incorrect. It doesn’t seem possible we call a function which has entirely different list of params than we provided.

2 Likes

Maybe super.write(newBuff) eventually calls the other write with more parameters, which is overridden. All methods are virtual in Kotlin.

2 Likes

https://t.ly/94PnH

https://t.ly/94PnH

this is the code

And what is the problem again? In the provided example you don’t even call any of implemented methods directly. I suspect @brunojcm is correct and you call one of these methods and internally it calls another one, but right now we have to guess what is your exact case and where do you see this exactly.

That 's all what I have, I am just trying to get what is happening here,
This is just a general example.

fun main() {
    UpperCaseWriter(FileWriter("log.txt")).use {
        it.write(
            """
            This is a test 
            another line 
            SOME UPPERCASE TEXT
        """.trimIndent())
    }
}

I think here, it.write(str) calls:

public void write(String str) throws IOException {
    write(str, 0, str.length())}
//and this write(str, 0, str.length())
//calls my overriden fun write that is:
    override fun write(str: String, off: Int, len: Int) {
        super.write(str.uppercase(), off, len)
    }
////as I am delegating to realwriter that it use all the methods except for the overriden ones, Am I right here?

Yes, you are right. There are no two separate objects: FilterWriter and UpperCaseWriter. There is only one object using a mix of methods from both classes, depending if you overridden them or not.

2 Likes