捕获多个允许 types/signatures 的块

Capturing blocks with multiple allowed types/signatures

是否可以在具有多个允许签名的方法中捕获块?

alias IoBlockFormatter = Severity, Time, String, String, IO -> Nil
alias StringBlockFormatter = Severity, Time, String, String -> String

class Formatter
  def initialize(@io : IO, &@block : IoBlockFormatter | StringBlockFormatter)
  end
end

在这个例子中,我定义了两种不同的函数类型,我想允许我的 Formatter class 可以接受的块是任何一种类型。我第一次尝试使用这两种类型的联合,但编译器抱怨期望的是 Function 类型,而不是两种 Proc 类型的联合。

expected block type to be a function type, not (Proc(Severity, Time, String, String, IO, Nil) | Proc(Severity, Time, String, String, String))

  def initialize(@io : IO, &@block : IoBlockFormatter | StringBlockFormatter)

您不能让一种方法采用多种块类型,因为块是根据方法签名键入的,而不是相反。一旦找到正确的方法,块参数的类型就会从非捕获块的 yield 和捕获参数的 &block 类型中推导出来。您也不能有两个具有相同参数的重载和一个块,即使出于类似原因使用不同的块也是如此。