您能告诉我这个Scala代码有什么问题吗?
package com.user.common
class Notification(message: String, next: Option[Notification]) {
def write(): String = {
message
}
def getAll(): Stream[Notification] = {
next match {
case Some(n) => Stream.cons(n, n.getAll())
case None => Stream.empty
}
}
}
case class Email(msg: String)
extends Notification(msg, None)
case class SMS(msg: String)
extends Notification(msg, Option(Email))
case class VoiceRecording(msg: String)
extends Notification(msg, Option(SMS))
编译器的错误如下所示。
[error] /common/Test.scala:15: type mismatch;
[error] found : Some[A]
[error] required: Option[com.user.common.Notification]
[error] case Some(n) => Stream.cons(n, n.getAll())
[error] ^
[error] /common/Test.scala:15: type mismatch;
[error] found : A
[error] required: com.user.common.Notification
[error] case Some(n) => Stream.cons(n, n.getAll())
[error] ^
[error] /common/Test.scala:15: value getAll is not a member of type parameter A
[error] case Some(n) => Stream.cons(n, n.getAll())
[error] ^
[error] /common/Test.scala:25: type mismatch;
[error] found : com.user.common.Email.type
[error] required: com.user.common.Notification
[error] extends Notification(msg, Option(Email))
[error] ^
[error] /common/Test.scala:28: type mismatch;
[error] found : com.user.common.SMS.type
[error] required: com.user.common.Notification
[error] extends Notification(msg, Option(SMS))
[error] ^
[error] 5 errors found
[error] (compile:compileIncremental) Compilation failed
我无法理解这个问题。同样,我不知道如何重组代码。我的基本想法是保持一个案例类的值并迭代它们直到我达到无。从顶级案例类到低级别案例类。
答案 0 :(得分:3)
case class SMS(msg: String)
extends Notification(msg, Option(Email))
case class VoiceRecording(msg: String)
extends Notification(msg, Option(SMS))`
在第二个参数中,您将在类类型上传递一个选项,而该类的实例是预期的
也许你想要的是
case class SMS(msg: String)
extends Notification(msg, Option(Email(msg)))
case class VoiceRecording(msg: String)
extends Notification(msg, Option(SMS(msg)))`