I currently have code like this: ``` override ...
# announcements
e
I currently have code like this:
Copy code
override 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?
p
Something like this maybe https://pl.kotl.in/4eS7G-xbb ?
🥇 1
e
Nice!
👍 1
(first-place medal for first-class types)
🥇 1
I modified your code to return the instance variable as the desired type. https://pl.kotl.in/cDt1J3zpr
p
Instead of
Copy code
if (savedState is T) (savedState as T) else null
you can just write
Copy code
savedState as? T
🙂
🤦‍♀️ 1
e
Thank you. As you can tell from the long variable names, I come from Java.
😄 1
I’ll be adding some sort of error reporting in the else branch so I think I’ll leave it as an
else
(unless you have a better idea).
I hope you don’t mind I looked you up on the interwebz. My grandfather went to college in Kharkiv about 100 years ago. I don’t think they taught functional programming then.
Actually, I should probably use the Elvis operator, not
if
.
p
My grandfather went to college in Kharkiv about 100 years ago.
Nice 🙂
Actually, I should probably use the Elvis operator, not
if
.
Sure, whatever is easier in your case.
e
This is pretty ugly:
Copy code
inline fun <reified T : ConnectionState> check() =
        savedConnectionState as? T ?: {
            Logger.error("savedConnectionState was $savedConnectionState, expected $T")
            null
        }()
Is there a way to include
T
in my error message or does the type get erased?
nm, I found the answer
p
You can write
Copy code
= (savedConnectionState as? T).also {
    it ?: Logger.error("savedConnectionState was ${savedConnectionState::class}, expected ${T::class}")
}
Or if check
Copy code
= (savedConnectionState as? T).also {
    if (it == null) Logger.error("...")
}
e
I really appreciate the Kotlin lesson. I’ve never used
also
before. That’s much more elegant.
p
let
,
apply
,
also
and
run
are amazing 🙂
e
Would you like to be credited in the commit message? I’m coding for Mozilla.
p
That would be very sweet 😊
1
e
Let me know if you ever want a referral to Mozilla (or to Google, where my husband works).
p
Thank you, I appreciate that.