Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin “Nothing”是表示该类型输入参数的合法用法吗';子类不重要吗?_Kotlin - Fatal编程技术网

Kotlin “Nothing”是表示该类型输入参数的合法用法吗';子类不重要吗?

Kotlin “Nothing”是表示该类型输入参数的合法用法吗';子类不重要吗?,kotlin,Kotlin,假设我有这样的接口: interface Car<T : Fuel?> { fun run(fuel: T) } interface Fuel { ... } 正如您所期望的,当您运行每辆车时,输出将如下所示 Run the petrol car Burn some petrol Run the electric car Use some electricity Run the perpetuum mobile 这是有效的。但我对这种结构不是100%满意。

假设我有这样的接口:

interface Car<T : Fuel?> {
    fun run(fuel: T)
}

interface Fuel {
    ...
}
正如您所期望的,当您
运行每辆车时,输出将如下所示

Run the petrol car
Burn some petrol

Run the electric car
Use some electricity

Run the perpetuum mobile


这是有效的。但我对这种结构不是100%满意。它对
无任何用途合法吗?
?这样的构造有更好的替代方案吗?

我的建议是使用自定义对象,如
objectnofuel
。使用
无?
时,您要么在某处保持常量
val noFuel=null
要么在调用
run
时传递可疑的
null
。使用显式对象时,它看起来更具可读性。
Nothing?
是一个具有单个值(
null
)的类型,因此符合al3c的说法。还有一种内置类型只有一个值:
Unit
,但我不知道这是否更好。我稍微简化了最初的问题。它实际上是关于非常相似的ViewModels的层次结构,这些ViewModels有时有一些输入可序列化的负载,有时没有。因此,也许这更像是通过
任何?
而不是
燃料
。。。
Run the petrol car
Burn some petrol

Run the electric car
Use some electricity

Run the perpetuum mobile