【问题标题】:this vs. (this) in ScalaScala 中的 this 与 (this)
【发布时间】: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,然后编辑问题。

标签: scala circe


【解决方案1】:

正如Luis Miguel Mejía Suárez 所指出的,这既不是语法错误也不是编译错误,而是当前版本的 IntelliJ IDEA Scala 插件(版本 2021.3.17)中的错误。使用括号是解决此问题的一种方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2015-01-22
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多