本文介绍了SBT 对 Scala 类型感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SBT 抛出以下错误:

SBT is throwing the following error:

value split is not a member of (String, String)
[error]       .filter(arg => arg.split(delimiter).length >= 2)

对于以下代码块:

implicit def argsToMap(args: Array[String]): Map[String, String] = {
val delimiter = "="
args
  .filter(arg => arg.split(delimiter).length >= 2)
  .map(arg => arg.split(delimiter)(0) -> arg.split(delimiter)(1))
  .toMap
}

谁能解释一下这里发生了什么?一些细节:

Can anyone explain what might be going on here?Some details:

java version "1.8.0_191"
sbt version 1.2.7
scala version 2.11.8

我在命令行和 intellij 上都试过.我也试过 Java 11 和 Scala 2.11.12 无济于事.

I've tried both on the command line and also with intellij. I've also tried Java 11 and Scala 2.11.12 to no avail.

我无法在另一台机器(不同的操作系统、SBT、IntelliJ 等)上复制它,我也可以编写一个最小的失败案例:

I'm not able to replicate this on another machine (different OS, SBT, IntelliJ, etc. though) and I can also write a minimal failing case:

value split is not a member of (String, String)
[error]     Array("a", "b").map(x => x.split("y"))

推荐答案

问题是 filter 方法是通过隐式添加到数组的.当您调用 args.filter(...) 时,args 将通过 Predef.refArrayOps 转换为 ArrayOps隐式方法.

The issue is that the filter method is added to arrays via an implicit.When you call args.filter(...), args is converted to ArrayOps via the Predef.refArrayOps implicit method.

您正在定义从 Array[String]Map[(String, String)] 的隐式转换.这个隐式比 Predef.refArrayOps 具有更高的优先级,因此被使用.

You are defining a implicit conversion from Array[String] to Map[(String, String)].This implicit has higher priority than Predef.refArrayOps and is therefore used instead.

所以args被转换成Map[(String, String)].该 Map 的 filter 方法需要一个 (String, String) => 类型的函数.布尔值 作为参数.

So args is converted into a Map[(String, String)]. The filter method of that Map would expect a function of type (String, String) => Boolean as parameter.

这篇关于SBT 对 Scala 类型感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:54