Hit a really strange issue today while trying to add an implicit method to Either.

implicit class EitherProvidesRollback[String,B](e: Either[String,B]) {
  def rollback(
    ss: Option[Session], overrideMsg: Option[String]): Either[String,B] = {

    e.fold(
      msg=> {
        ss.map(_.rollback)
        // found String required java.lang.String, FTW
        // Left(i18n(overrideMsg.getOrElse(msg)))

        // behold, the horrible hack
        Left(i18n(overrideMsg.getOrElse(msg).toString).asInstanceOf[String])
      },
      Right(_)
    )
  }
}

the i18n method takes a String, which AFAICT is exactly what it's getting. The workaround, as per this thread, is to T <: String in the implicit class' type signature. It appears Predef might be at play here.

Is there a way to get this working without horrendous runtime casting while at the same time preserving the type signature as exactly String?

Thanks

有帮助吗?

解决方案

There are two types called String in your code. One is java.lang.String, the other is the type parameter String that EitherProvidesRollback takes. I'm guessing using String as a type parameter to EitherProvidesRollback is your problem. It should only require B as its type parameter.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top