gpt4 book ai didi

scala - 非变量类型参数

转载 作者:行者123 更新时间:2023-12-02 06:14:46 25 4
gpt4 key购买 nike

我有以下型号:

case class Questionnaire(List(Question[_])
case class Question[A](text: String, Answer[A])
case class Answer[A](value: A)

我正在尝试根据类型设置问卷中的所有答案(答案可以是 String、Double 或 LocalDate 类型):
val questionnaire = getMockQuestionnaireWithoutAnswers()
questionnaire.questions.map {
case x: Question[String] => //...default the answer.value to some random string
case x: Question[Double] => //...default the answer.value to some random double
case x: Question[LocalDate] => //...default the answer.value to some random date
}

但我得到了错误:

类型模式 examplenamespace.Question[String] 中的非变量类型参数 String 未选中,因为它已被删除消除。

我不想将所有类型包装成这样的类:
case class StringQuestion(question: Question[String])

避免此错误的最佳方法是什么?

最佳答案

类型删除是消除匹配表达式中提供的参数类型,这意味着 Question[String] 之间的差异和 Question[Int]在运行时丢失。

避免这种情况的一种方法是提供该类型的具体实现,以便 JVM 无法“删除”它。

我过去使用过这种结构。可能还有其他方法,但这很简单:

case class Answer[A](a:A)
case class Question[A](text: String, answer: Answer[A])
case class Questionnaire(questions: List[Question[_]])

// concrete types
trait StringQuestion extends Question[String]
trait DoubleQuestion extends Question[Double]
trait IntQuestion extends Question[Int]

def resolve(questions: List[Question[_]]): List[String] = {
questions.map {
case x: StringQuestion => "Stringy"
case x: DoubleQuestion => "Doubly"
case x: IntQuestion => "Inty"
}
}

关于scala - 非变量类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40237011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com