我正在尝试在 Scala 3 中编译以下代码(适用于 Scala 2.13):
import scala.concurrent.duration._
@main
def main(): Unit = {
case class AAA(d: FiniteDuration)
val duration1 = 5.seconds
implicit val what = AAA(duration1)
}
但出现以下错误:
递归值duration1需要类型implicit val what = AAA(持续时间1)
使参数非隐式修复了错误。为什么?
尝试
import scala.concurrent.duration._
@main
def main(): Unit = {
case class AAA(d: FiniteDuration)
val duration1 = 5.seconds
implicit val what: AAA = AAA(duration1)
}
或
import scala.concurrent.duration._
@main
def main(): Unit = {
case class AAA(d: FiniteDuration)
val duration1 = 5.seconds
given AAA = AAA(duration1)
}
作为一般准则:始终明确地归因所有给定/隐式的类型。这是编译时类型级计算的分配,最好指定要将给定值分配给什么类型。