gpt4 book ai didi

scala - 为什么不能绑定(bind)通配符类型参数是Scala?

转载 作者:行者123 更新时间:2023-12-04 06:40:30 24 4
gpt4 key购买 nike

我有一个类型的对类:

class TypedPair[T]

我想将某个函数应用于它们的异构序列:
def process[T](entry: TypedPair[T]) = {/* something */}

为什么这不起作用?
def apply(entries: TypedPair[_]*) = entries.foreach(process)

它失败并出现错误:
error: polymorphic expression cannot be instantiated to expected type;
found : [T](TypedPair[T]) => Unit
required: (TypedPair[_]) => ?
def apply(entries: TypedPair[_]*) = entries.foreach(process)

我不记得在Java中遇到过这个问题......

最佳答案

在这种情况下,编译器无法确定匿名方法。添加 dummy 参数时,您还更改了语法以帮助编译器使用它,因此以下内容将起作用:

def apply(entries: TypedPair[_]*) = entries.foreach(process(_))

关于scala - 为什么不能绑定(bind)通配符类型参数是Scala?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4302656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com