0

I know that this type of question is already asked but it is not working for me so please tell me how to get the below code working:

 if (a1!= null && a2!= null && message != null) {
     if (intent!= null) {
         Thread.sleep(5000)
         ChangePicAsyncTask(context, message).execute(a1, a2)           //Error line 
     }
 }

Here "message" is the declared as private var class level nullable variable. Below line "Thread.sleeep(..)" it shows that error. I tried to put an if check but its also not working so please give some suggestions how can i solve this error.

Michael
  • 57,169
  • 9
  • 80
  • 125
sak
  • 1,230
  • 18
  • 37

2 Answers2

3

Variable message could have been changed (eg become null) after the Thread.sleep(). So perhaps use let.

message?.let { Thread.sleep(5000) ChangePicAsyncTask(context, it).execute(a1, a2) }

Bryan
  • 46
  • 2
0

To ensure that it doesn't change, you must assign it to a final variable, like so:

 val a1 = a1
 val a2 = a2
 val message = message
 if (a1 != null && a2 != null && message != null) {
     if (intent!= null) {
         Thread.sleep(5000)
         ChangePicAsyncTask(context, message).execute(a1, a2) // Smart casts now work
     }
 }

If that seems tacky, then you could use the approach described here.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • `val a1 = a1` `val a2 = a2` `val message = message` does this compile? –  Jul 20 '18 at 12:21
  • @mTak yes, why wouldn't it compile? – EpicPandaForce Jul 20 '18 at 12:21
  • Why? What does `val a = 0` `val a = a` mean? –  Jul 20 '18 at 12:23
  • Assign the value to a final variable (so `val`). – EpicPandaForce Jul 20 '18 at 12:24
  • But it's the same name `a` for 2 variables? –  Jul 20 '18 at 12:25
  • It's `a1` and `a2` which is clearly two different names? – EpicPandaForce Jul 20 '18 at 12:26
  • The assignment is val a1=a1. This means assigning the value of previously declared variable a1 to a new declared variable by the same name a1 in the same scope –  Jul 20 '18 at 12:28
  • What you don't understand is *I did not ask you*. This was way to tell you you made a mistake. I knew this was wrong and I expected from you to correct it. As for the part *without me possibly knowing that* you could ask for clarification. As for the part *Learn the language* I have to admit that I'm still learning and not trying to find excuses for my mistakes. –  Jul 20 '18 at 13:01
  • Not to mention, this ***is*** the right way of doing it if you have multiple mutable field variables. – EpicPandaForce Jul 20 '18 at 13:23
  • It's not my fault the question provided incomplete code. I will stop caring about this nonsense beyond this point. I've already spent way too much energy on an unnecessary flame war anyway. – EpicPandaForce Jul 20 '18 at 13:43