类型Right [Nothing,Map [String,String]]的表达式不符合预期的类型Left [String,Nothing]

时间:2019-03-20 09:45:53

标签: scala

我有以下代码,无法编译:

object PcpProtocol {

  private type PcpKV = String

  private val findPublicKey: List[PcpKV] => Either[String, Map[String, String]] = kv =>
    kv
      .filter(_.contains("PUBLIC:"))
      .foldLeft(Left("Can not find the public key from SAP.")) { (_, a) =>
        a.split(":").toList match {
          case List(key, value) => Right(Map(key -> value))
        }

      }
} 

编译器抱怨:

type mismatch;
[error]  found   : scala.util.Right[Nothing,scala.collection.immutable.Map[String,String]]
[error]  required: scala.util.Left[String,Nothing]
[error]           case List(key, value) => Right(Map(key -> value))  

我在做什么错了?

2 个答案:

答案 0 :(得分:5)

您可以通过明确指定类型来帮助编译器。

  private val findPublicKey: List[PcpKV] => Either[String, Map[String, String]] = kv =>
    kv
      .filter(_.contains("PUBLIC:"))
      .foldLeft[Either[String, Map[String, String]]](Left("Can not find the public key from SAP.")) { (_, a) =>
        a.split(":").toList match {
           case List(key, value) => Right(Map(key -> value))
        }
    }

答案 1 :(得分:3)

编译器无法正确推断类型AFURLSessionManager *downloadManager1 = [[AFURLSessionManager alloc] initWithSessionConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration]; NSURLSessionDownloadTask *downloadTask; downloadTask=[downloadManager1 downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){ NSURL *aURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; return [aURL URLByAppendingPathComponent:[response suggestedFilename]]; }completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { } ]; [downloadTask resume]; ,因为它会将其范围缩小到Either[String, Map[String, String]]

您可以明确添加类型:

Left[String]

或:

.foldLeft(Left("Can not find the public key from SAP."): Either[String, Map[String, String]]) { (_, a) =>

如果您在项目中使用猫,也可以使用:

.foldLeft[Either[String, Map[String, String]]](Left("Can not find the public key from SAP.")) { (_, a) =>

为其中一个创建类型别名通常是一个好主意,例如:

"Can not find the public key from SAP.".asLeft[Map[String, String]]

这可以使您更具可读性:

type ErrorOr[T] = Either[String, T]