Ellen Spertus
10/11/2019, 8:05 PMoverride fun onReject(token: String) {
if (savedConnectionState is ConnectionState.Authenticating) {
// do something
} else {
// complain
}
}
override fun onSend(message: String) {
if (savedConnectionState is ConnectionState.ReadyToSend) {
// do something
} else {
// complain
}
}
Is there a way to create a check() method that takes a type (e.g., ConnectionState.Authenticating) as an argument and tests whether the instance variable savedConnectionState is that type?Pavlo Liapota
10/11/2019, 8:13 PMEllen Spertus
10/11/2019, 8:14 PMEllen Spertus
10/11/2019, 8:32 PMEllen Spertus
10/11/2019, 8:32 PMPavlo Liapota
10/11/2019, 8:36 PMif (savedState is T) (savedState as T) else null
you can just write
savedState as? T
🙂Ellen Spertus
10/11/2019, 8:37 PMEllen Spertus
10/11/2019, 8:38 PMelse (unless you have a better idea).Ellen Spertus
10/11/2019, 8:40 PMEllen Spertus
10/11/2019, 8:40 PMif.Pavlo Liapota
10/11/2019, 8:42 PMMy grandfather went to college in Kharkiv about 100 years ago.Nice 🙂
Pavlo Liapota
10/11/2019, 8:44 PMActually, I should probably use the Elvis operator, notSure, whatever is easier in your case..if
Ellen Spertus
10/11/2019, 8:44 PMinline fun <reified T : ConnectionState> check() =
savedConnectionState as? T ?: {
Logger.error("savedConnectionState was $savedConnectionState, expected $T")
null
}()Ellen Spertus
10/11/2019, 8:50 PMT in my error message or does the type get erased?Ellen Spertus
10/11/2019, 8:51 PMPavlo Liapota
10/11/2019, 8:55 PM= (savedConnectionState as? T).also {
it ?: Logger.error("savedConnectionState was ${savedConnectionState::class}, expected ${T::class}")
}
Or if check
= (savedConnectionState as? T).also {
if (it == null) Logger.error("...")
}Ellen Spertus
10/11/2019, 8:56 PMalso before. That’s much more elegant.Pavlo Liapota
10/11/2019, 8:57 PMlet, apply, also and run are amazing 🙂Ellen Spertus
10/11/2019, 9:03 PMPavlo Liapota
10/11/2019, 9:05 PMEllen Spertus
10/11/2019, 9:06 PMPavlo Liapota
10/11/2019, 9:08 PM