Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this vs. (this) in Scala

Tags:

scala

circe

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?

like image 696
Johann Heinzelreiter Avatar asked Nov 05 '22 23:11

Johann Heinzelreiter


1 Answers

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.

like image 51
Johann Heinzelreiter Avatar answered Dec 10 '22 00:12

Johann Heinzelreiter