0

我有一个trait带有泛型参数的方法,其中包含我试图将默认实现定义为“空”的方法。

trait MetaBase[T <: Throwable] {
  ...
  def riskWithEvent[V](
    vToEvaluate: => V,
    failureTEvent: FailureBase[T, V] => Unit = _ => ()
  ): TryBase[T, V] =
    ...
}

我在 . 之后的下划线处收到“缺少参数类型”错误failureTEvent: FailureBase[T, V] => Unit =。我无法弄清楚如何让 Scala 编译器放弃在那个时候必须知道类型信息,因为它不被使用或不需要。

我考虑将参数更改为:

failureTEvent: Option[FailureBase[T, V] => Unit] = None

但是,我不喜欢客户现在必须将他们的功能包装在Some(). 我更希望允许他们不指定参数,或者指定没有包装器的参数。

非常感谢对此的任何指导。

4

1 回答 1

3

实际上,它的V参数有问题。

这里是-Ylog:typer -Ytyper-debug

|    |    |    |    |    |-- ((x$1) => ()) : pt=FB[T,?] => Unit BYVALmode-EXPRmode (site: value g in MB) 
<console>:13: error: missing parameter type
       trait MB[T <: Throwable] { def f[V](g: FB[T, V] => Unit = _ => ()): Unit = () }
                                                                 ^
|    |    |    |    |    |    \-> <error> => Unit

或者,

scala> case class FB[T, V](t: T, v: V)
defined class FB

这有效:

scala> trait MB[T <: Throwable, V] { def f(g: FB[T, V] => Unit = _ => ()): Unit = () }
defined trait MB

这不会:

scala> trait MB[T <: Throwable] { def f[V](g: FB[T, V] => Unit = _ => ()): Unit = () }
<console>:13: error: missing parameter type
       trait MB[T <: Throwable] { def f[V](g: FB[T, V] => Unit = _ => ()): Unit = () }
                                                                 ^

或者只是 take Any,因为函数在 arg 中是逆变的:

scala> trait MB[T <: Throwable] { def f[V](g: FB[T, V] => Unit = (_: Any) => ()): Unit = () }
defined trait MB

与默认 arg 类型相关的其他链接:

https://issues.scala-lang.org/browse/SI-8884

https://issues.scala-lang.org/browse/SI-7095

Scala case class.type 不带参数

于 2016-09-21T22:33:52.310 回答