Rob Elliot
12/05/2023, 10:02 AMprivate val jwtVerifier = (
JWT.require(Algorithm.RSA256(jwkRSAProvider))
.acceptLeeway(3) as JWTVerifier.BaseVerification
)
.build(clock)
So I pulled out an extension function as so:
private val jwtVerifier = JWT
.require(Algorithm.RSA256(jwkRSAProvider))
.acceptLeeway(3)
.castTo<JWTVerifier.BaseVerification>()
.build(clock)
@Suppress("UNCHECKED_CAST")
private fun <B> Any.castTo(): B = this as B
Is there an existing equivalent of castTo
I'm missing?
Is there any way to ensure that the receiver is a supertype of the target type, without having to pass both as type arguments at the call site?Sam
12/05/2023, 10:12 AMlet
.
.acceptLeeway(3)
.let { it as JWTVerifier.BaseVerification }
.build(clock)
That way you get the formatting you want, but still get the IDE warnings and other inspections that come with using as
.Rob Elliot
12/05/2023, 10:16 AMSam
12/05/2023, 10:16 AM@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
fun <A, B : A> @kotlin.internal.Exact A.castTo() = this as B
Then using _
at the call site:
.acceptLeeway(3)
.castTo<_, JWTVerifier.BaseVerification>()
.build(clock)
But the resulting behaviour is still less intelligent than the built-in IDE inspections 😞
Any().castTo<_, String>() // ✅
"Hello".castTo<_, Int>() // ❌
("Hello" as Any).castTo<_, Int>() // ✅
At the end of the day, you'll always be able to come up with some example of a downcast that looks fine but fails at runtimeRob Elliot
12/05/2023, 10:18 AMprivate val jwtVerifier = JWT
.require(Algorithm.RSA256(jwkRSAProvider))
.acceptLeeway(3)
.withAudience(audience)
.build(clock)
fun Verification.build(clock: Clock): JWTVerifier = (this as JWTVerifier.BaseVerification).build(clock)
Sam
12/05/2023, 10:19 AMSam
12/05/2023, 10:19 AMSam
12/05/2023, 10:19 AM