简体   繁体   English

为什么如果对于V <:Seq [Int]当V是Seq后代映射并且zip操作返回Seq [Int]时

[英]Why if for V <: Seq[Int] when V is a Seq descendant map and zip operations return a Seq[Int]

As mentioned in the title i don't understand why these function doesn't compile and are asking for a Seq. 正如标题中所提到的,我不明白为什么这些函数不能编译并要求Seq。

def f1[V <: Seq[Int]](v: V): V = v.map(_ + 1)
def f2[V <: Seq[Int]](v: V): V = v.zip(v).map{ case (a, b) => a + b }

error: type mismatch;
found   : Seq[Int]
required: V

I have the following workaround : 我有以下解决方法:

def f1[V <: Seq[Int]](v: V): V = v.map(_ + 1).asInstanceOf[V]
def f2[V <: Seq[Int]](v: V): V = v.zip(v).map{ case (a, b) => a + b }.asInstanceOf[V]

But i would like to know if it exist another solution. 但我想知道它是否存在另一种解决方案。 If not what is the cost of casting something like that, is it O(1) or O(n) with n the Seq size. 如果不是这样的铸造成本是多少,是O(1)还是O(n),其中n为Seq大小。

Because 因为

v.map(_ + 1).asInstanceOf[V]

can easily fail: map is only guaranteed to return a Seq[Int] , which may or may not happen to be an instance of V when you run the code. 很容易失败: map只保证返回一个Seq[Int] ,当你运行代码时,它可能会或可能不会成为V一个实例。

One example would be V = SeqView.Filtered , where map returns a SeqView.Mapped . 一个例子是V = SeqView.Filtered ,其中map返回SeqView.Mapped

If not what is the cost of casting something like that, is it O(1) or O(n) with n the Seq size. 如果不是这样的铸造成本是多少,是O(1)还是O(n),其中n为Seq大小。

The cost of casting with asInstanceOf is always O(1). 使用asInstanceOf进行投射的成本始终为O(1)。 In some cases it's actually a no-op and the cost is 0. 在某些情况下,它实际上是无操作,成本为0。

Let's go through how your function is compiled: 让我们来看看你的函数是如何编译的:

def f1[V <: Seq[Int]](v: V): V = v.map(_ + 1)

1/ You declared V as a sub-type of Seq[Int] . 1 /您将V声明为Seq[Int]的子类型。 So V can be viewed by the compiler as Seq[Int] . 因此编译器可以将V视为Seq[Int]

2/ Inside function, v.map(_ + 1) return type is Seq[Int] because it's using a Seq method. 2 / Inside函数, v.map(_ + 1)返回类型是Seq[Int]因为它使用的是Seq方法。

3/ V is the declared return type. 3 / V是声明的返回类型。 This doesn't match the actual return type, which is Seq[Int] . 这与实际返回类型不匹配,即Seq[Int] And your compiler can't view Seq[Int] as V because because there's no type bound that says [V >: Seq[Int]] . 并且您的编译器无法将Seq[Int]视为V ,因为没有类型绑定显示[V >: Seq[Int]]

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

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