Unnecessary Temporary Instantiation
ID |
kotlin.unnecessary_temp_instantiation |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
performance, redundant |
Description
Reports throwaway boxed-wrapper constructions such as Integer("42") or
Double("1.5"). Each one allocates a Java boxed wrapper from a string just
to immediately unbox its primitive value. Kotlin offers direct literals
(42, 1.5, 3L) and idiomatic string conversions ("42".toInt(),
"1.5".toDouble()) that skip the allocation and read more clearly.
Rationale
// Bad
val a = Integer("42") // FLAW — use 42 or "42".toInt()
val b = Long("3") // FLAW
val c = Double("1.5") // FLAW
// Good
val a = 42
val b = 3L
val c = 1.5
val d = "42".toInt() // OK — explicit parse
val e = "1.5".toDouble() // OK — explicit parse
The boxed wrapper constructors are deprecated on the Java side as well —
Integer(String) has been deprecated since JDK 9 in favour of
Integer.parseInt(String) or Integer.valueOf(String). Kotlin’s literal
and extension-based conversions are the idiomatic replacements.
Remediation
Replace Wrapper("literal") with the corresponding Kotlin literal when the
argument is a constant, or with String.toInt() / String.toDouble() / etc.
when the argument is a runtime string.
The rule fires only when the constructor has exactly one argument, so it does not interfere with rare multi-argument overloads.