hey! I don't know if this makes much sense, but he...
# announcements
p
hey! I don't know if this makes much sense, but here it goes, imagine I have test utility method that among other things needs to check the type contained in an Either.Left, how would this be? is it even possible? is it just plain stupid trying to do so?
Copy code
fun testStuff([...], type: ?????) {
  [...]
  assert((foo as Either.Left).a is type)
  [...]
}
Should
type
be
KClass
or
KType
?? I'm a bit lost
s
You can use
Class<T>.isAssignableFrom(otherClass)
There is a similar API for
KClass
but it requires kotlin-reflect.
p
nice! thanks! I'll try right now
k
Or if possible you can have your function take a reified type parameter and just use
is T
then.
m
I created this helper for that. A bit of overkill, but makes test syntax quite clean Usage example:
Copy code
fun verifyLeftUsage() {
        val subject = "something".left()

        verifyLeft<String>(subject) {
            it shouldEqual "something"
        }
    }
Copy code
/**
 * For testing a function that returns an Either, and want to verify that a Left was returned
 *
 * If a Right is returned, an exception will be thrown with a descriptive message.
 *
 * The validation function will recieve the Left of the Either cast to class EE, where EE is the specific error
 * class on the Left side.
 *
 * If the Left is not of the correct type, a class cast exception will be thrown.
 *
 * The validation can then focus on validating the specific properties of the error.
 *
 * @sample com.bns.cbttdsshrd.testhelper.assertj.ArrowKtSamples.verifyLeftUsage
 * @param EE The type of the Notification that is expected
 * @param subject The Either item to confirm is a `Left`
 * @param validation The Lambda that will receive the Left as a parameter so further verifications can be performed on
 * the object
 */
inline fun <reified EE> verifyLeft(subject: Either<*, *>, validation: (EE) -> Unit) {
    subject.fold({
        if (it is EE) {
            validation(it)
        } else {
            throw AssertionError(
                MESSAGE_LEFT_CORRECT_CLASS.format(
                    it?.javaClass?.simpleName ?: "NULL",
                    EE::class.simpleName
                )
            )
        }
    }, { fail(MESSAGE_IS_NOT_LEFT) })
}
p
hey!
thank you all, in the end I went with Karel's option, which imo was more concise and simpler, but I might also create an extension later on when needed, so thanks for the idea Mike!