0

I have converted java file to kotlin using android studio inbuilt file converter. It show below error.

[SMARTCAST_IMPOSSIBLE] Smart cast to 'ReminderRequester' is impossible, because 'ReminderRequester' is a mutable property that could have been changed by this time

My code snippet is as below.

    private var sReminderInstance: ReminderRequester? = null

    val instance: ReminderRequester
        get() {
            if (sReminderInstance == null) {
                sReminderInstance = ReminderRequester()
            }
            return sReminderInstance; // ERROR: Smart cast to 'ReminderRequester' is impossible, because 'ReminderRequester' is a mutable property that could have been changed by this time
        }

I have checked similar type of question but I can not able to understand it properly.

What is meaning of above error and how to fix it?

Priyank Patel
  • 12,244
  • 8
  • 65
  • 85

2 Answers2

2

2 solutions

1) Force the return type to have the same type as the property

return sReminderInstance!!;

2) Change the property type to match the return type

val instance: ReminderRequester?
Samuel Robert
  • 10,106
  • 7
  • 39
  • 60
1

The error you are seeing is because ReminderRequester is not the same as ReminderRequester?. By using sReminderInstance!! you are in a sense casting a nullable to a non-nullable object, guaranteeing to the compiler that you know it won't ever be null (but you could be wrong).

...Smart cast to 'ReminderRequester' is impossible,...

This error is occurring on the return statement, and if you are using IntelliJ IDEA, there is a red indicator under sReminderInstance. The error message is sort of weak, but it means that because you are turning sReminderInstance from a function (get()) that has a return type of ReminderRequester (a non-nullable type), the compiler needs to cast the returned variable to ReminderRequester. But, like I said, sReminderInstance is not a ReminderRequester (it is a ReminderRequester? i.e., a nullable type).

You will see this error a lot in converted Java code. Where ever you are use to handling possibly null variables, they are often turned into nullable types. Sometimes, just checking if it is null before using it as a non-nullable will work. That's called a "smart cast". Other times, the compiler deems that threading might defeat the smart cast, and disallows it (in which case you can use the !! when you are sure threading won't be an issue).

In summary,

What is meaning of above error and how to fix it?

It means the compiler attempted a "smart cast". "Smart cast" is the terminology for trying to convert a nullable type into it's non-nullable equivalent. And smart cast will not always be allowed, even though you checked if the variable was null. To fix, you will usually apply !! to the variable being cast.

Les
  • 10,335
  • 4
  • 40
  • 60