Frustration w kotlin compiler, I needed an entry p...
# coroutines
d
Frustration w kotlin compiler, I needed an entry point for connecting and executing redis operations from Java (the one for kotlin was trivial to write). I made one which returned a
CompletableFuture
. I was shocked that the compiler didn't flag illegal casts and that in runtime, the caller logged but swallowed the cast exception. IDK if it was bc it was on a future or something up the stack from the caller that swallowed it. Here's the erroneous code (
pool
is
suspend
). The fix is to use
RedisClusterCommands
not its subclass
RedisCommands
Copy code
fun <T> withBlockingConnection(body: (RedisCommands<String, String>) -> T): CompletableFuture<T> =
        CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>).future {
            val connection = pool.borrowObject()
            try {
                val commands = when (connection) {
                    is StatefulRedisConnection -> connection.sync()
                    is StatefulRedisClusterConnection -> connection.sync()
                    else -> throw IllegalStateException("Redis connection is not a known type $connection")
                } as RedisCommands<String, String>

                body(commands)
            } finally {
                pool.returnObject(connection)
            }
        }
j
The cast is not illegal if it's a subclass of what you actually have. That's the whole point of casts. Usually if you have to cast, something is wrong elsewhere. I'm also surprised you don't get an unchecked cast warning given that you have generics here. Btw, you are creating a coroutine scope without storing it for proper cancellation/lifecycle handling, which is generally a problem too.