ermac10k
04/28/2021, 9:35 AMJonathan Olsson
04/28/2021, 9:38 AMcrummy
04/28/2021, 9:42 AMval
in Kotlin though, while const
is something different, right?Pavel Sidyakin
04/28/2021, 9:45 AMconst val DEBUG_LOG_ENABLED = BuildConfig.BUILD_TYPE == "debug"
inline fun debugLog(block: LogWrapper.() -> Unit) {
if (DEBUG_LOG_ENABLED) LogWrapper.block()
}
If you remove "const" runtime check will be occurred.Vampire
04/28/2021, 9:49 AMconst
has to be a compile-time constant.
So this shouldn't compile, should it?
Unless maybe if BUILD_TYPE
is a const
too.Pavel Sidyakin
04/28/2021, 9:50 AMPavel Sidyakin
04/28/2021, 9:52 AMpublic final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String BUILD_TYPE = "debug";
}
ermac10k
04/28/2021, 9:52 AMPavel Sidyakin
04/28/2021, 9:57 AMPavel Sidyakin
04/28/2021, 9:58 AMermac10k
04/28/2021, 9:59 AMJonathan Olsson
04/28/2021, 11:35 AMthat description seems to matchin Kotlin though, whileval
is something different, right?const
val
is a read-only local variable. Compare that to const
: https://kotlinlang.org/docs/properties.html#compile-time-constants
I would assume a val
is similar to a Java final
and a const
would most closely resemble a static final
?
I don't really know why the poopwas given to the wikipedia article, but I might be missing some context related to the question. Besides the optimisations already known to OP const
has great semantic utility. At least, that is my view of it.ermac10k
04/28/2021, 11:37 AMstatic final ~ companion object { val ... }
fyiJonathan Olsson
04/28/2021, 11:38 AMJonathan Olsson
04/28/2021, 11:39 AMstatic final
would probably better be replaced by const
in a kotlin program.ermac10k
04/28/2021, 11:39 AMJonathan Olsson
04/28/2021, 11:43 AMclass A {
companion object {
val MY_CONSTANT = 123
}
}
compared to this:
const val MY_CONSTANT = 123
Vampire
04/28/2021, 11:47 AMval MY_CONSTANT = 123
Vampire
04/28/2021, 11:47 AMMY_CONSTANT
in the A
namespace or notVampire
04/28/2021, 11:48 AMVampire
04/28/2021, 11:48 AMconst
is like a static final
in Java for which you use upper-case letters, as you should usually just use that for real constants and not for any static final
.Pavel Sidyakin
04/28/2021, 11:59 AMconst val QUERY = "SELECT id FROM table"
@Dao
interface ADao {
@Query(QUERY)
fun query(): Int
}
Won't compile:
val QUERY = "SELECT id FROM table"
@Dao
interface ADao {
@Query(QUERY)
fun query(): Int
}
ermac10k
04/28/2021, 12:41 PMcompanion object { const val ABC = "abc" }
disclaimer: it’s not my code 😉Vampire
04/28/2021, 12:45 PMVampire
04/28/2021, 12:45 PMprivate
, then I'd say it is non-sense clutter and a top-level private const val
would achieve the sameephemient
04/28/2021, 3:01 PMephemient
04/28/2021, 3:02 PMBoolean.parseValue("false")
)ephemient
04/28/2021, 3:03 PMconst val
vs val
ermac10k
04/29/2021, 5:06 AM