首页 > 解决方案 > Kotlin(null 不能转换为非 null 类型)自定义日历实现

问题描述

我正在尝试在 Java 中使用库https://github.com/kizitonwose/CalendarView(它是用 Kotlin 制作的)。在这个库中有一个选择日期的例子。在示例中,它显示了这样做:

    private fun selectDate(date: LocalDate) {
    if (selectedDate != date) {
        val oldDate = selectedDate
        selectedDate = date
        oldDate?.let { exThreeCalendar.notifyDateChanged(it) }
        exThreeCalendar.notifyDateChanged(date)
        updateAdapterForDate(date)
    }
}

在尝试在我自己的 android 项目中复制它之后,我写了这个:

    private void selectDate(LocalDate date){
        if(selectedDate != date){
            // oldDate is null
            // date is not null
            LocalDate oldDate = selectedDate;
            selectedDate = date;
            if (oldDate != null){
                calendarView.notifyDateChanged(oldDate);
            }
            calendarView.notifyDateChanged(date);
            updateAdapterForDate(date);
            }
        }

当我的片段启动时,它以今天的日期作为参数(不为空)调用 selectDate() 方法。它给出了一个错误

calendarView.notifyDateChanged(date);

 null cannot be cast to non-null type com.kizitonwose.calendarview.ui.CalendarAdapter

我想知道如何达到相同的结果

oldDate?.let { exThreeCalendar.notifyDateChanged(it) }

在 Java 中,或者如果我的代码有其他不正确的地方。谢谢你的帮助。

标签: javaandroidkotlinviewcalendar

解决方案


请注意错误消息中的类型。这不是datenull ,而是 type 的东西CalendarAdapter,我怀疑

private val calendarAdapter: CalendarAdapter
    get() = adapter as CalendarAdapter

看起来adapter应该设置在setup,也许你没有调用它?


推荐阅读