1

I have the following code, that does not compile:

object PcpProtocol {

  private type PcpHead = String
  private type PcpBody = String
  private type PcpValidity[A] = Either[String, A]
  private val PcpIndicator = "pcp-channel:apc"

  implicit val pcpProtocol: Protocol[PcpProtocol] = new Protocol[PcpProtocol] {
    override def encode(text: String): PcpProtocol = ???

    override def decode(msg: PcpProtocol): String = ???
  }

  private val validatePcp: PcpValidity[PcpHead] = (head: String) => {
    if (head.contains(PcpIndicator)) {
      Right(head)
    } else {
      Left("The message does not correspond to SAP PCP protocol")
    }
  }
}

The error message says:

 type mismatch;
[error]  found   : String => scala.util.Either[String,String]
[error]  required: com.sweetsoft.PcpProtocol.PcpValidity[com.sweetsoft.PcpProtocol.PcpHead]
[error]     (which expands to)  scala.util.Either[String,String]
[error]   private val validatePcp: PcpValidity[PcpHead] = (head: String) => {  

I can not figure out the error. What is wrong?

softshipper
  • 32,463
  • 51
  • 192
  • 400
  • Not found type "Protocol", "PcpProtocol". At least these two are obviously just missing. And the `(head: String) => { ... }` for an `Either[String, String]` doesn't make any sense at all, it's obviously not an `Either`, it's a function literal. – Andrey Tyukin Mar 19 '19 at 20:13
  • @AndreyTyukin Sorry I did not get it, what you mean? Could you please go more into detail? – softshipper Mar 19 '19 at 20:20
  • 1) If you took your code and tried to run it with `scala`, it would complain that `Protocol` and `PcpProtocol` are undefined symbols. Add them, otherwise it's not an [mcve]. 2) Every expression of shape `(head: String) => body` is obviously of type `Function1[String, B]`, where `B` is the type of `body`, it cannot possibly unify with an `Either[X, Y]` for any `X, Y`. Type aliases don't matter at all in this case. – Andrey Tyukin Mar 19 '19 at 20:22
  • `validatePcp` is a function, that has the argument `head`. – softshipper Mar 19 '19 at 20:23
  • But your type declaration guarantees that `validatePcp` is an `Either[String, String]`. How is that supposed to fit together? – Andrey Tyukin Mar 19 '19 at 20:24
  • I think, I misunderstood the concept of the anonymous function. – softshipper Mar 19 '19 at 20:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190326/discussion-between-zero-coding-and-andrey-tyukin). – softshipper Mar 19 '19 at 20:25

0 Answers0