generics - Kotlin强制参数类型为字符串, bool 值或数字

标签 generics kotlin primitive-types

我有一个用例,我向服务器发送一些数据(作为分析数据),这些数据始终是StringBooleanNumber

如何强制调用方仅发送数字, bool(boolean) 值或字符串,而不发送其他任何对象?

以下情况应能工作:

userProperties: MutableMap<String, in AnyPrimitive> = mutableMapOf(),

userProperties.put("someKey", 1)
userProperties.put("someKey", 1.2f)
userProperties.put("someKey", "someValue")
userProperties.put("someKey", true)

但不是
userProperties.put("someKey", myCustomObjectInstance)

我尝试的方法是创建一个抽象类EventData,该类实现CharSequenceNumber。但这要求每个人都创建这些类的实例,而不仅仅是发送数字或字符串。

我可以放一个逻辑来检查类型并引发异常,但我更希望在编译时对其进行限制。

最佳答案

如果要从使用 Angular 简化,请声明send函数,如下所示:

fun send(arg: Any) {
    //Validations here:
    if (!validate(arg)) throw IllegalArgumentException("...")

    //Actual send code here...
}

private fun validate(arg: Any): Boolean {
    return (arg is String || arg is Boolean || arg is Number)
}

请注意,这不是在编译时强制执行,而是运行时失败。因此,如果有人将
send(RandomObject)

编译将成功。在运行时,它将失败。

关于generics - Kotlin强制参数类型为字符串, bool 值或数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61076223/

相关文章:

java - int 上的余数运算符导致 java.util.Objects.requireNonNull?

java - 使用 Java 中的基本类型创建具有内部矩阵表示的 Matrix 泛型类

c# - 通用 TryParse

c# - 通用扩展方法解析失败

java - 在 Java 中对泛型进行排序

Android ScrollView 没有完全滚动到底部

kotlin - Kotlin Flow 的 Collect 是否只是内部 kotlinx.coroutines API?

kotlin - Kotlin类实例断言不正确

c# - 实现一个非常特殊的通用签名

java - 常规编程: How do you return two Types of primitive ('int and ' string') from "get" method?