https://kotlinlang.org logo
Title
p

pepe

06/17/2019, 11:49 AM
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?
fun testStuff([...], type: ?????) {
  [...]
  assert((foo as Either.Left).a is type)
  [...]
}
Should
type
be
KClass
or
KType
?? I'm a bit lost
s

Sergey Chelombitko

06/17/2019, 11:59 AM
You can use
Class<T>.isAssignableFrom(otherClass)
There is a similar API for
KClass
but it requires kotlin-reflect.
p

pepe

06/17/2019, 12:05 PM
nice! thanks! I'll try right now
k

karelpeeters

06/17/2019, 12:27 PM
Or if possible you can have your function take a reified type parameter and just use
is T
then.
m

Mike

06/17/2019, 1:10 PM
I created this helper for that. A bit of overkill, but makes test syntax quite clean Usage example:
fun verifyLeftUsage() {
        val subject = "something".left()

        verifyLeft<String>(subject) {
            it shouldEqual "something"
        }
    }
/**
 * 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

pepe

06/18/2019, 7:20 AM
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!