Read-Only enforcement on function arguments

I do get read-only is somewhat a key feature for kotlin but at points, it seems to be adding more to my code base than reducing as the language is supposed to be doing i.e

fun getString(from: Int, to: Int): String {
    var to = to
    // move char cursor to start from position
    fseek(file, from.long, i)
    var string = ""

    while (--to > 0) {

        string += nextChar
    }
    return string
}

Why not have the capability to define the read-only state of my function arguments like in class constructors which are already there? class Foo(var name = “foo”)

fun getString(from: Int, var to: Int): String {
    // move char cursor to start from position
    fseek(file, from.long, i)
    var string = ""

    while (--to > 0) {
        string += nextChar
    }
    return string
}

Kotlin does not have immutability (at least yet). It does have read-only values (those are not guaranteed not to change). As for function arguments, all of those always passed by reference (not true for primitives, but those could nor be changed anyway).

edited the immutability section. cant there be something like
programmer written code

fun getString(from: Int,var to: Int): String {
    moveCursor(from,i)
    var string = ""

    while (--to > 0) {
        val char = nextChar
        if (char == (-1).charVal) throw Error("End of file character can not be part of a token string")

        string += char
    }
    return string
}

compiler generated IR in respect of

fun getString(from: Int,  toReference: Int): String {
    var to = toReference
    // move char cursor to start from position
    fseek(file, from.long, i)
    var string = ""
    while (--to > 0) {
       string += nextChar
    }
    return string
}

now yes it uses the pass by reference, but once declared as var it can have var to = toReference auto-generated inside the IR of the function?

This is not the only instance I have had to recreate (var to) section and reassign making it fell repetitive since that is what the function requires and does have to make some sort of work around for it. i.e reasigning

Your code seems to be rather pointless since you do not use your to variable inside the cycle. You can easily replace it by repeat(to). But if you really want to use it, it is much safer to use for(i in to downTo 0).

1 Like