【发布时间】:2022-01-23 13:23:15
【问题描述】:
我使用 Scala circe 库将案例类 Message 的对象转换为 JSON,并从它们的 JSON 表示创建 Message 对象。该类实现如下:
import io.circe
import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
import io.circe.parser
import io.circe.syntax._
object Message {
implicit val measurementDecoder = deriveDecoder[Message]
implicit val measurementEncoder = deriveEncoder[Message]
def fromJson(jsonString: String): Either[circe.Error, Message] =
parser.decode[Message](jsonString)
}
case class Message(id: Int, text: String) {
def toJson() = (this).asJson.noSpaces
def toJson2() = this.asJson.noSpaces // syntax error: No implicit arguments of type: Encoder[Message.this.type]
}
我的观点是方法toJson的实现。虽然此变体有效
def toJson() = (this).asJson.noSpaces
变种
def toJson() = this.asJson.noSpaces
导致语法错误
No implicit arguments of type: Encoder[Message.this.type]
那么 Scala 中的 this 和 (this) 有什么区别?
【问题讨论】:
-
您遇到的错误是什么?
-
语法错误是:
No implicit arguments of type: Encoder[Message.this.type],但前提是this周围的括号被省略。 -
现在我很困惑。在这个问题的第一个版本中,您遇到了编译错误。现在,这是一个语法错误。这是两个非常不同的事情。两者中的哪一个?特别是,错误消息的 text 听起来不像是语法错误。
-
我无法重现它:scastie.scala-lang.org/BalmungSan/yBZzq0deQ5i8QOW87R5puA/2 - 这意味着错误不是真实的,只是您的 IDE 中的一些错误。或者,您分享的代码不足以重现错误;请创建一个真正重现错误的 Scastie,然后编辑问题。