【问题标题】:Kotlin: Difference in definition of CollectionKotlin:集合定义的差异
【发布时间】:2017-06-10 08:51:51
【问题描述】:

这在 Kotlin 中有什么区别:

val customerProducts = mutableMapOf<Customer, Set<Product>>()

还有这个:

val customerProducts: MutableMap<Customer, Set<Product>> = mutableMapOf()

【问题讨论】:

  • 第二条语句无法编译。

标签: dictionary collections kotlin


【解决方案1】:

您的第二个示例无法编译,但我假设您的意思是:

val customerProducts: MutableMap<Customer, Set<Product>> = mutableMapOf()

回答这个问题,没有区别。您必须提供您在某处创建的Map 的类型参数,然后它将在其他位置推断。由您决定使用哪一个。

  • 如果您在赋值左侧提供此信息,并带有显式变量类型,它将由mutableMapOf 函数推断。
  • 如果将其提供给mutableMapOf 函数的右侧,则会推断出变量的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2010-09-08
    • 2017-05-04
    • 2014-10-05
    • 2012-01-21
    相关资源
    最近更新 更多