我有一个检查其泛型类型参数的函数,如果该类型是预期值之一,则对其进行适合该类型的操作。如果类型是意外的,则会引发异常。
inline fun <reified T> convert(functionName: String, vararg args: Any?): T {
val obj: Any = executeJSFunction(functionName, *args)
val builtInClasses = arrayOf<KClass<*>>(Int::class, String::class, Boolean::class)
@Suppress("UNCHECKED_CAST")
return when {
T::class in builtInClasses ->
obj as T
T::class.companionObjectInstance as? DataClassFactory<T> != null ->
(T::class.companionObjectInstance as DataClassFactory<T>).fromV8Object(obj as V8Object)
else ->
throw IllegalArgumentException("No converter for type ${T::class}")
}
}
这有效,但它在运行时进行检查。如果泛型类型参数不是预期的类型之一,我想找到一种获取编译错误而不是运行时异常的方法。这可能吗,也许有合同?
// should compile, as Int is one of the supported types
val intResult: Int = convert("intFunction")
// should fail to compile, as Double is unsupported
val doubleResult: Double = convert("doubleFunction")