【问题标题】:What is this parameter type _>: with <: in Scala?这个参数类型 _>: 和 <: 在 Scala 中是什么?
【发布时间】:2018-04-16 18:17:42
【问题描述】:

我有一个参数化的泛型类型,其中泛型类型来自我单独定义的 Case 类。

这些是

case class TypeA(user_id: String,
                   device_id: String) extends Serializable


case class TypeB(user_id: String,
                   device_id: String,
                   org_id: String,
                   app_name: String) extends Serializable

我使用 Map 函数读取数据集,基于通用类型架构

val res = this.readHandlersMap.map(s => s._1 match {

case "a" => {
  (s._1, s._2.read[TypeA]((Encoders.product[TypeA].schema)).asInstanceOf[Dataset[TypeA]])
}

case "b" => {
   (s._1, s._2.read[TypeB]((Encoders.product[TypeB].schema)).asInstanceOf[Dataset[TypeB]])    
}
});

检查res 的输出后,我知道它是类型

Map[String, Dataset[_ >: TypeA with TypeB <: Serializable with Product]]

我不明白这种类型的含义。 _&gt;:withs 在这种类型中做了什么?当我尝试将res 声明为Dataset[Serializable] 类型时,我得到一个错误。如果我添加TypeC,这个类型会是什么?

【问题讨论】:

    标签: scala generics methods


    【解决方案1】:

    这些基本上是定义的泛型类型的上限和下限:

    例如:

    Car <: Vehicle //it means car is subtype of vehicle 
    Fruit >: Mango //fruit is super type of the mango
    

    这意味着我们可以将汽车实例放在车辆堆栈上。以及水果堆上的芒果实例。

    Map[String, Dataset[_ >: TypeA with TypeB <: Serializable with Product]]
    

    这一行表示 Dataset 是 where 类型。 _ 是 TypeA 的超类型,TypeB 是 Serializable 的子类型。

    【讨论】:

    • 谢谢,帮了大忙。我能够将表达式简化为 Dataset[_ &lt;: Serializable with Product] 并正确编译。
    猜你喜欢
    • 2012-02-21
    • 2014-12-11
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多