Kotlin value class 踩坑: lint 检查 (Error: Use Double.valueOf instead [UseValueOf])

136 阅读1分钟
value class Foo(value value: Double?)

这段代码的问题将会导致 gradlew :xxx:lintDebug 报告类似下面的报错内容

> Lint found errors in the project; aborting build.

  Fix the issues identified by lint, or create a baseline to see only new errors.
  To create a baseline, run `gradlew updateLintBaseline` after adding the following to the module's build.gradle file:
  ```
  android {
      lint {
          baseline = file("lint-baseline.xml")
      }
  }
  ```
  For more details, see https://developer.android.com/studio/write/lint#snapshot

  Lint found 1 errors, 0 warnings. First failure:

  demo/Demo.kt:10: Error: Use Double.valueOf(3750.0) instead [UseValueOf]
              foo = Foo(3750.0),
                    ~~~~~~~~~~~~~~~~~~~~~~~~

  The full lint text report is located at:
    demo/build/intermediates/lint_intermediate_text_report/debug/lintReportDebug/lint-results-debug.txt

这是因为 value class 是一个内联类, 它会在编译时拆包. 可空的值将使内联失去效果

另外, value class 不能继承但是可以实现接口. 但注意: 实现接口后, value class将失去内联能力, 因此这种用法失去了使用value class的意义.