For a value class, the parameter always generates,...
# getting-started
a
For a value class, the parameter always generates,
Copy code
Property "xxx" is never used
• Is it normal to use
@Suppress("unused")
for every value class? • And why does the linter not recognize this special case for a value class?
c
That is not normal. Please paste sample code for context.
2
a
Oh really? That's encouraging... My typical use case is an inner class like the following:
Copy code
@JvmInline
    value class Id(private val value: String)
and for each one, I get
c
yes. you have defined it as
private
, implying you intend to use it within the class (you don’t, hence the warning). Remove
private
or use the property inside the class.
a
Thanks very much for the explanation. Interesting that the examples in the docs are private
c
huh. yea. they are either incorrect (s/b just
val
) or incomplete (should show use of the prop).
thank you color 1
Here’s a couple examples of how I typically use value classes for trivial types (where type-safety is desired). I don’t personally like having a public val, would rather keep things private.
Copy code
@JvmInline
public value class Password(private val value: String) {
    override fun toString(): String = value
}

@JvmInline
public value class Id(private val value: String) {
    override fun toString(): String {
        return "Id(value='$value')"
    }
    public fun asString() : String = value
}
s
The equals and hashCode operations still use the private property, though, so arguably it's never truly unused. https://youtrack.jetbrains.com/issue/KTIJ-20509
thank you color 1
k
For passwords, I prefer to prevent inadvertently outputting the password (e.g. in a log message):
Copy code
@JvmInline
value class Password(private val value: String) {
    override fun toString() = "***"
    fun asPlaintextString() = value
}
That way when you have to pass the actual password text (e.g. to an API) the class forces you to realise that you're passing a password in plain view. Credit for the idea: https://void2unit.onrender.com/post/inline+password/
👍 1