Scala 3 隐式参数中递归值需要类型错误

问题描述 投票:0回答:1

我正在尝试在 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)

使参数非隐式修复了错误。为什么?

scala implicit scala-3
1个回答
0
投票

尝试

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)
}

作为一般准则:始终明确地归因所有给定/隐式的类型。这是编译时类型级计算的分配,最好指定要将给定值分配给什么类型。

© www.soinside.com 2019 - 2024. All rights reserved.