Is it possible to set default value, if argument v...
# getting-started
p
Is it possible to set default value, if argument variable name is named the same as property variable? For example:
Copy code
const val name = "String"

fun getSmth(name: String = name) = TODO("")
In a class scenario, I could use
this
keyword, like so:
Copy code
object X {
    const val name = "String"

    fun getSmth(name: String = this.name) = TODO("")
}
I know I can rename stuff, but I'm just wondering if it's possible to achieve that somehow
j
I know you're aware you can rename, but I just wanted to point out that it's a strange problem to have. The parameter is a variable, it could have different values based on the use case, but the constant is.. well.. constant. So it means the constant only defines a specific value, one of many that could fit the parameters. The name should probably reflect that, meaning that it wouldn't (couldn't?) match a parameter name. In this example,
name
is a general name. It could have different values depending on the named thing. The constant can't be named
name
, because it has to be the name of something specific. It could be
myThingName
for instance.
Could you please share your actual use case here?
As far as the question itself is concerned, I don't know the answer, but I think it's not possible
m
Have you tried fully qualifying the constant when using it for the default value.
p
Hm, I guess you mean constant should be named
NAME
, I guess you're right 🙃
full qualifier works yeah 👍
m
That's not what he means, but that is true also. A constant with the same name as a parameter is just strange regardless of capitalization. Having the same name indicates that they represent the same thing, but how can you represent a constant and a variable/parameter. The question to ask is what is special about your constant name that is different then what other values they might pass to
getSmth
. That will give you a clue about how to name the constant.
j
Exactly. Thank you @mkrussel. And yes we could capitalize, but that is besides the point. I actually kept the style from the question to better illustrates my point about semantics. Also, incidentally I would prefer an UpperCamelCase style rather than SCREAMING_SNAKE_CASE.
Fully qualified name works indeed, so long as you do have a package name (meaning, the constant is not in the root package, which is the case in your example - unless you omitted the
package
clause). And also, you have to be sure that you don't have a variable name in scope that would match a single-identifier package. For instance, if your package is
example
but you also have a local property named
example
,
example.name
doesn't compile: https://pl.kotl.in/h5MpcW1zY
p
ok, gotcha. Thanks for info 🍺