将 Kotlin 属性委托与 by 一起使用时出现 NullPointerException (NPE)

     2023-02-19     301

关键词:

【中文标题】将 Kotlin 属性委托与 by 一起使用时出现 NullPointerException (NPE)【英文标题】:NullPointerException (NPE) when using Kotlin property delegate with by 【发布时间】:2020-11-17 07:28:59 【问题描述】:

我有一个类,它在文本字段中接受用户输入并使用提供的函数将它们转换为任何类

class GenericTextFieldDelegate<T>(
    private val initBlock: () -> TextView,
    private val getConversion: (String?) -> T?,
    private val setConversion: (T?) -> String? =  it?.toString() 
    ) 
    private val textView: TextView by lazy  initBlock() 

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T? =
        getConversion(textView.text?.toString())

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) 
        textView.text = setConversion(value)
    

我这样做是为了当我有 TextViews 时我可以这样做

class IntegerInputView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attributeSet, defStyleAttr), DataInput<Int> 

override var value: Int? by GenericTextFieldDelegate(
     inputET ,
    getConversion =  it?.toIntOrNull() ,
    setConversion =  it.toString() 
)
...

我有一个具有上述自定义视图的片段,当我有时

override var tareWeight: Kg?
    get() = tareWeightInput.value
    set(value) 
        tareWeightInput.value = value
    

一切正常,我真正想做的是

override var tareWeight: Kg? by tareWeightInput

将这些行添加到IntegerInputView

...

operator fun getValue(thisRef: Any?, property: KProperty<*>): Int? = value

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int?) 
    this.value = value


override var value: Int? by GenericTextFieldDelegate(
...

当我构建、运行和加载片段时,我得到下面的堆栈跟踪。我哪里错了?

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer com.gameforeverything.storekeeper.customViews.IntegerInputView.getValue(java.lang.Object, kotlin.reflect.KProperty)' on a null object reference
        at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInFragment.getGrossWeight(Unknown Source:7)
        at com.gameforeverything.storekeeper.fragments.weighInFragment.WeighInPresenter.getNetWeight(WeighInPresenter.kt:40)

【问题讨论】:

【参考方案1】:

您的属性委托本身(本例中为tareWeightInput)为空。

您可以通过检查堆栈跟踪来判断是这种情况:它注意到由于 NPE 而失败的方法调用是IntegerInputView.getValue。由于这是在委托上调用属性委托方法调用以检索属性值,因此我们知道委托必须为空。

您的属性委托是View,所以我怀疑它正在以某种方式动态检索,可能是findViewById 调用的结果。您需要确保包含委托的变量在检索时不为空。考虑这个类似的例子:

import kotlin.reflect.KProperty

class FooDelegate 
    private var value: Int = 0
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = value
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int)  this.value = value 


class Foo 
    private lateinit var delegate: FooDelegate
    val bar by delegate
    
    init 
        delegate = FooDelegate()
    


fun main() 
    println(Foo().bar)

这会崩溃,因为它试图在变量初始化之前设置委托。在这种情况下,Kotlin 会更早地抛出错误,但由于 Kotlin/Java 互操作,这可能在您的示例中被 platform types 掩盖。

【讨论】:

将 Qute TypeSafe 模板与 Kotlin 一起使用时出现 java.lang.UnsatisfiedLinkError

】将QuteTypeSafe模板与Kotlin一起使用时出现java.lang.UnsatisfiedLinkError【英文标题】:java.lang.UnsatisfiedLinkErrorwhenusingQuteTypeSafeTemplateswithKotlin【发布时间】:2021-07-2614:36:30【问题描述】:当尝试将QuarkusQuteTypesafeTemplates与Kotlin一起使用时... 查看详情

将 QuerydslPredicateExecutor 与 JpaRepository 一起使用时出现 IllegalAccessException

】将QuerydslPredicateExecutor与JpaRepository一起使用时出现IllegalAccessException【英文标题】:IllegalAccessExceptionwhenusingQuerydslPredicateExecutorwithJpaRepository【发布时间】:2022-01-0402:45:41【问题描述】:应用:kotlin1.6jdk17(也试过8和11)gradle7.3spr 查看详情

Kotlin 注释处理器在将 Room 与 A​​ndroid Studio 3.0 beta7 一起使用时出现编译时错误

】Kotlin注释处理器在将Room与A​​ndroidStudio3.0beta7一起使用时出现编译时错误【英文标题】:KotlinannotationprocessorgivescompiletimeerrorwhileusingRoomwithAndroidStudio3.0beta7【发布时间】:2018-03-1800:04:11【问题描述】:我正在使用AndroidStudio3.0Bet... 查看详情

将插入与 KeyHolder 一起使用时出现 ArrayIndexOutOfBoundsException

】将插入与KeyHolder一起使用时出现ArrayIndexOutOfBoundsException【英文标题】:ArrayIndexOutOfBoundsExceptionwhenusinginsertwithKeyHolder【发布时间】:2018-11-1111:42:38【问题描述】:有一个例子,适用于这个版本:Stringsql="insertintoalbum(name)VALUES(:name... 查看详情

将 AutoMapper 与实体框架一起使用时出现异常

】将AutoMapper与实体框架一起使用时出现异常【英文标题】:ExceptionusingAutoMapperwithEntityFramework【发布时间】:2012-11-1705:49:25【问题描述】:我正在尝试使用实体框架将Automapper包含到项目中,这是我的DTO类:publicclassFunctionDtopublicin... 查看详情

将 Jackson JSON 库与骆驼一起使用时出现异常

】将JacksonJSON库与骆驼一起使用时出现异常【英文标题】:ExceptionusingJacksonJSONlibrarywithcamel【发布时间】:2014-03-0123:06:26【问题描述】:我在将JacksonJSON库与骆驼一起使用时遇到问题。例外是:FailedToCreateRouteException:Failedtocreateroute... 查看详情

将 TensoBoard 与 TPU 一起使用时出现 UnimplementedError

】将TensoBoard与TPU一起使用时出现UnimplementedError【英文标题】:UnimplementedErrorwhileusingTensoBoardwithTPU【发布时间】:2021-02-2817:58:29【问题描述】:我目前正在使用TPU训练我的模型。不幸的是,在使用TensoBoard和TPU时出现X错误。如果我... 查看详情

将 objcopy 与“薄存档”文件一起使用时出现问题

】将objcopy与“薄存档”文件一起使用时出现问题【英文标题】:Problemwhileusingobjcopywith"thinarchive"file【发布时间】:2019-02-2714:12:36【问题描述】:请使用以下shell命令重现问题:#createsubdirectorymkdirsubdir#createsourcefileswithdummyfu... 查看详情

kotlin-代理属性(by)

...对象和真实对象实现相同的接口,代理对象持有真实对象Kotlin-代理属性(by)Kotlin中,委托的实现依靠于关键字by,by表示将实现接口的真实对象(by后边的实例)保存在代理对象的内部,比如SportsManager类继 查看详情

将 Firebase 与 RecyclearView 一起使用时出现错误

】将Firebase与RecyclearView一起使用时出现错误【英文标题】:IhaveanerrorwhenusingFirebasewithRecyclearView【发布时间】:2018-06-1617:54:00【问题描述】:我在运行我的应用程序时遇到这些错误:致命异常:主进程:com.google.example.adinaranayaragh... 查看详情

将 Typescript 与 React-Redux 一起使用时出现类型错误

】将Typescript与React-Redux一起使用时出现类型错误【英文标题】:TypeErrorwhenusingTypescriptwithReact-Redux【发布时间】:2016-08-2820:33:12【问题描述】:我正在尝试将react-redux与typescript一起使用,当我尝试使用connect()和mapStateToProps注入道... 查看详情

将多个 Include() 与嵌套 Select() 一起使用时出现 EntityCommandExecutionException

】将多个Include()与嵌套Select()一起使用时出现EntityCommandExecutionException【英文标题】:EntityCommandExecutionExceptionwhenusingmultipleInclude()withnestedSelect()【发布时间】:2018-09-3017:23:31【问题描述】:我在MySQL中使用实体框架。假设我有以下... 查看详情

将 retfofit 与 MVVM 一起使用时出现错误

】将retfofit与MVVM一起使用时出现错误【英文标题】:IamgettingerrorwhileusingretfofitwithMVVM【发布时间】:2021-06-2514:48:22【问题描述】:我正在尝试使用带有MVVM架构的改造来获取数据。当我想在控制台上打印数据时,它可以工作。但是... 查看详情

将 Sequence 与 HSQL 一起使用时出现“InvalidDataAccessResourceUsageException”

】将Sequence与HSQL一起使用时出现“InvalidDataAccessResourceUsageException”【英文标题】:\'InvalidDataAccessResourceUsageException\'whenusingSequencewithHSQL【发布时间】:2015-03-1113:13:06【问题描述】:我在Hibernate/Oracle和测试阶段使用JPA,使用HSQL。... 查看详情

将折线与本机地图一起使用时出现空引用错误

】将折线与本机地图一起使用时出现空引用错误【英文标题】:NullreferenceerrorwhileusingPolylinewithreact-nativemaps【发布时间】:2019-11-0819:55:43【问题描述】:当我使用折线时,它给了我这个错误:attempttoinvokeinterfacemethod\'java.util.iterato... 查看详情

保存数据时出现问题,将 CoreData 与 SwiftUI 一起使用

】保存数据时出现问题,将CoreData与SwiftUI一起使用【英文标题】:Problemsavingdata,usingCoreDatawithSwiftUI【发布时间】:2020-07-2106:29:55【问题描述】:我刚开始使用CoreData和SwiftUI。在关注thisseriesoftutorial之后。而且我面临着无法按预期... 查看详情

将 Shrinksafe 与 IBM JRE 一起使用时出现 MalformedInputException

】将Shrinksafe与IBMJRE一起使用时出现MalformedInputException【英文标题】:MalformedInputExceptionwhileusingShrinksafewithIBMJRE【发布时间】:2010-09-1115:17:12【问题描述】:在尝试使用Shrinksafecustom_rhino.jar构建Dojo时,我得到了MalformedInputException。... 查看详情

将 Facebook 插件与 Unity 一起使用时出现 ActivityNotFoundException

】将Facebook插件与Unity一起使用时出现ActivityNotFoundException【英文标题】:ActivityNotFoundExceptionwhenusingFacebookpluginwithUnity【发布时间】:2015-12-0321:50:02【问题描述】:我正在使用Unity5.2.2p2、FacebookUnitySDK7.2.2和Prime31的AndroidIAB插件2.9。... 查看详情