【发布时间】:2017-11-06 00:51:55
【问题描述】:
scala> val names = List("Peter", "Paul", "Mary")
names: List[String] = List(Peter, Paul, Mary)
scala> names.map(_.toUpperCase)
res12: List[String] = List(PETER, PAUL, MARY)
在这种情况下,下划线表示唯一的输入参数,即名称元素。该字符串被隐式转换为 StringOps 并调用 toUpperCase。
但是,这不起作用:
scala> names.map(StringOps.toUpperCase _)
<console>:14: error: value toUpperCase is not a member of object scala.collection.immutable.StringOps
names.map(StringOps.toUpperCase _)
我认为这种语法是我从 toUpperCase 方法获取函数引用的方式。
【问题讨论】:
-
我试过你的代码,但得到了不同的错误。那是错误:未找到:值 StringOps。 StringOps 没有伴随对象。 String to StringOps 使用隐式 def augmentString(x: String): StringOps defined in Predef .
标签: scala