gpt4 book ai didi

scala - 通过方法/构造函数参数隐式与隐式使用

转载 作者:行者123 更新时间:2023-12-04 17:54:34 24 4
gpt4 key购买 nike

此代码编译并执行预期的操作

class MyList[T](list: T)(implicit o: Ordering[T])

但是这不会:

class MyList2[T](list: T) {
val o = implicitly[Ordering[T]]
}

我不明白为什么。在第一个示例中,当构造类时,编译器会发现 Ordering 是隐式的,因为它知 Prop 体类型 T。但在第二种情况下,它也应该找到隐含的,因为 T 已经是一个具体类型。

最佳答案

In the first example when the class is being constructed the compiler will find the Ordering implicit because it will know the concrete type T.

在第一个示例中,编译器需要在范围内有一个隐式的 Ordering[T] 才能找到它。编译器本身不会“弥补”隐式。由于您直接要求通过第二个参数列表提供一个,如果存在这样的隐式,它将被传递给类构造函数。

But in the second case it should also find the implicit since T will already be a concrete type.

T 在编译时是具体类型这一事实并不能帮助编译器找到它的隐含类型。当我们说 T 是具体类型时,您必须记住,在调用点,T 只是一个泛型类型参数,仅此而已。如果你不帮助编译器,它就不能保证在范围内具有隐式。您需要让该方法提供一个隐含的方法,这可以通过 Context Bound 来完成:

class MyList2[T: Ordering](list: T)

这需要在编译时存在类型 T 的排序。从语义上讲,这等同于您的第二个参数列表。

关于scala - 通过方法/构造函数参数隐式与隐式使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022157/

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