假设您想约束一个类型变量来实现某个接口.你可能会这样写:
from typing import TypeVar, Callable
T = TypeVar('T', Callable)
class Foo(Generic[T]):
...
>> TypeError: A single constraint is not allowed
Run Code Online (Sandbox Code Playgroud)
为什么Python对这种类型约束的使用不满意?在这方面,PEP 484和Python源代码无益.
注意:在我的特定情况下,我感兴趣的是约束一个类型变量来实现一个抽象基类,但原理是相同的.
Chisel 教程使用了似乎是<>操作符的东西,这对我来说是完全陌生的。它有什么作用?
还有,它从哪里来?这个运算符在其他 Scala 库甚至其他语言中是否有传统含义?
下面是一个使用示例,来自 Chisel Generator Bootcamp 练习,第 3.2 节:
class MyQueue extends Module {
// Example circuit using a Queue
val io = IO(new Bundle {
val in = Flipped(Decoupled(UInt(8.W)))
val out = Decoupled(UInt(8.W))
})
val queue = Queue(io.in, 2) // 2-element queue
io.out <> queue
}
Run Code Online (Sandbox Code Playgroud) 当隐式类声明中发生转换时,编译器未能选择正确的隐式转换方法。在下面的示例中,我有一个Foo[T]类和一个隐式Helper类,它采用 aFoo并提供一个print方法。该 print 方法调用show,它本身是一个由 on 隐式转换提供的方法Foo。
问题是有两种可能的转换提供show:一种转换Foo[T]为 a Bar[T],另一种转换Foo[Array[T]]为 a BarArray[T]。这个想法是,当我们有一个Foo包含数组的时候,我们想要应用更具体的BarArray转换。据我了解,编译器首先选择具有最具体类型的转换。
这在正常上下文中起作用,如下例所示,但print在隐式Helper类中的方法的上下文中中断。在那里,show调用了相同的方法,因此我希望应该应用相同的转换。然而,在这种情况下,编译器总是选择Bar转换,即使它有Foo[Array[T]]并且应该选择BarArray转换。
出了什么问题?
最小失败代码示例:
package scratch
import scala.language.implicitConversions
class Foo[T](val value: T) {}
object Foo {
implicit def fooToBar[T](foo: Foo[T]): Bar[T] = {
new Bar(foo.value)
}
implicit def fooArrayToBarArray[T](foo: Foo[Array[T]]): BarArray[T] = {
new …Run Code Online (Sandbox Code Playgroud)