Get a proper parameter name within inheritance

I have an issue to get a right parameter here in method but it’s fine with a variable. How to show that I need Foo@bar, not Buzz@bar here in chad1()?

class Foo(
    bar: Bar,
) : Buzz(bar = bar) {
    val chad = bar.chad // Fine
    fun chad1() = bar.chad // Doesn't see chad because Buzz's bar doesn't have it
}

You can’t access bar inside chad1(), because bar is a constructor parameter and is available only during the initialization of the object. You have to make it a val if you want to use it anywhere outside the constructor.

2 Likes

Hm, if it’s available with parameters, why not with methods? I can’t make it val because it

hides member of supertype and needs ‘override’ modifier

So, I need to rename it also and it’s not good. What if I do some JS-style combo like:

val a = fun() = bar.chad

Don’t sure if it’s not messy, need to check it later.

Parameters are initialized during object initialization, functions can be invoked at any later time, when bar is not available anymore.

You can just give it a different name than its super property:

class Foo(
    bar: Bar,
) : Buzz(bar = bar) {
    private val bar2 = bar
    val chad = bar.chad // Fine
    fun chad1() = bar2.chad
}

yeah, it’s currently best available alternative. Or maybe overriding is not so bad (instead of passing all the parameters in a child).

Is giving Buzz.bar a protected getter an option for you?

If not, I think I would prefer the definition of the function as val:

class Foo(bar: Bar) : Buzz(bar) {
    val chad = bar.chad
    val chad1 = { bar.chad }
}

Obviously this preference is said under the precondition that Buzz.bar is a val.

Something shorter than I wrote as a function.

Are you just trying to reference something from super?

open class Base {
    val bar: String

    constructor(bar: String) {
        this.bar = bar
    }
}

class SubType : Base {
    val myBar: String
    val superBar: String
        get() = super.bar

    constructor(bar: String) : super("Super $bar") {
        myBar = bar
    }
}

fun main() {
    val foo = SubType("bar")
    println(foo.bar)
    println(foo.myBar)
    println(foo.superBar)
}

I’d recommend going through something like Atomic Kotlin–it seems like it would answer a lot of your questions better than I can :slight_smile: .

Alternatively, maybe you’re trying to keep a reference to the constructor param bar? You can just save it under another name in the constructor. I typed out the constructors to help make them more obvious instead of leaving them inline with the class declaration. Notice how SubType keeps its own reference to the constructor param under a new name myBar.

1 Like