繁体   English   中英

Scala类型系统和继承

[英]Scala type system and inheritance

采取以下Scala代码:

import scala.collection.mutable.HashMap

class father[T,K:Numeric] extends HashMap[T,K]
class sonA[T] extends father[T, Long]
class sonB[T] extends father[T, Double]

def func_sonA[T](x: List[T]) = {
    // code
    new sonA[T]
}

def func_sonB[T](x: List[T]) = {
    // code
    new sonB[T]
}

val strList = List("one", "two", "three", "four")
val intList = List(1,2,3,4)
val both:List[List[Any]] = List(strList, intList)

val mapped = both.map(x =>
    x match {
        case i:List[String] => func_sonA(i)
        case i:List[Int] => func_sonB(i)
    }
)

mapped的类型为: List[father[_ >: String with Int, _ >: Long with Double : AnyVal]]

_>:到底是什么意思?

String with Int背后的想法是什么,它有什么用? 似乎它可以无限期地增长( String with Int with Double With Long with... )。

如何在不丢失类型信息的情况下将mapped的类型指定为List[father]List[father[Any, Any]]

我很难找到答案,因为短语_>:搜索结果不是很相关。


编辑:

为了说明造成此问题的实际问题,我想使用带有List[father[Any, Any]]输入的函数,但无法传递mapped 我收到类型不匹配错误。

功能:

def bar(x: List[father[Any, Any]]) = {
    println(x)
}
bar(mapped)

错误:

Error:(52, 9) type mismatch;
 found   : List[father[_ >: String with Int, _ >: Long with Double <: AnyVal]]
 required: List[father[Any,Any]]
    bar(mapped)
        ^

_ >: String with Int基本上意味着该类型是StringInt List[String]情况下,您会得到一个sonA[String] ,因此在此情况下会返回一个father[String, Long] ;在List[Int]情况下,您将分别sonB[Int]和一个father[Int,Double]所以与father在一起, father的第一种类型为StringInt ,第二种类型为LongDouble

关于其他问题:

如何在不丢失类型信息的情况下将映射的类型指定为List[father]List[father[Any, Any]]

你为什么要那样? 当前类型实际上比List[father]List[father[Any,Any]].更具体List[father[Any,Any]].

编辑

好吧,我知道你想要什么。

基本上,您想要实现的目标是:

val mapped: List[father[Any,Any]] = both.map(x =>
  x match {
    case i:List[String] => func_sonA(i)
    case i:List[Int] => func_sonB(i)
  }
)

这里的问题是,目前

class father[T,K] extends HashMap[T,K]

Scala编译器不知道例如father[String,Long]应该是father[Any,Any]的子类型(这不会自动由于StringLongAny子类型而导致)。 因此,要告诉Scala上面的方法适用,您需要在两个类型参数中使father类协变:

class father[+T,+K] 

这样做的问题是,您正在扩展HashMap[T,K] 但是此类仅在第一类型参数T是协变的,而在K不是。

因此,此代码实际上有效,但未扩展HashMap

class father[+T,+K]
class sonA[T] extends father[T, Long]
class sonB[T] extends father[T, Double]

def func_sonA[T](x: List[T]) = {
  // code
  new sonA[T]
}

def func_sonB[T](x: List[T]) = {
  // code
  new sonB[T]
}

val strList = List("one", "two", "three", "four")
val intList = List(1,2,3,4)
val both = List(strList, intList)

val mapped: List[father[Any,Any]] = both.map(x =>
  x match {
    case i:List[String] => func_sonA(i)
    case i:List[Int] => func_sonB(i)
  }
)

def bar(x: List[father[Any, Any]]) = {
  println(x)
}
bar(mapped)

有关协方差的更多信息,请点击这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM