Johann Heinzelreiter
Johann Heinzelreiter

Reputation: 819

this vs. (this) in Scala

I use the Scala circe library to convert objects of the case class Message to JSON and also to create Message objects from their JSON representation. This class is implemented as follows:

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

My point is the implementation of the method toJson. While this variant works

def toJson() = (this).asJson.noSpaces

the variant

def toJson() = this.asJson.noSpaces

leads to the syntax error

No implicit arguments of type: Encoder[Message.this.type]

So what's the difference between this and (this) in Scala?

Upvotes: 6

Views: 147

Answers (1)

Johann Heinzelreiter
Johann Heinzelreiter

Reputation: 819

As pointed out by Luis Miguel Mejía Suárez it is neither a syntax nor a compile error, but a bug in the current version of the IntelliJ IDEA Scala plugin (version 2021.3.17). Using parentheses is a way to get around this problem.

Upvotes: 3

Related Questions