加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala奇怪的地图功能行为

发布时间:2020-12-16 10:08:30 所属栏目:安全 来源:网络整理
导读:为什么以下代码有效? scala List(1,2,3) map "somestring"res0: List[Char] = List(o,m,e) 它适用于2.9和2.10. 展望typer: [master●●] % scala -Xprint:typer -e 'List(1,3) map "somestring"' ~/home/folone/backend[[syntax trees at end of typer]] /
为什么以下代码有效?

scala> List(1,2,3) map "somestring"
res0: List[Char] = List(o,m,e)

它适用于2.9和2.10.
展望typer:

[master●●] % scala -Xprint:typer -e 'List(1,3) map "somestring"'                                                                                ~/home/folone/backend
[[syntax trees at end of                     typer]] // scalacmd2632231162205778968.scala
package <empty> {
  object Main extends scala.AnyRef {
    def <init>(): Main.type = {
      Main.super.<init>();
      ()
    };
    def main(argv: Array[String]): Unit = {
      val args: Array[String] = argv;
      {
        final class $anon extends scala.AnyRef {
          def <init>(): anonymous class $anon = {
            $anon.super.<init>();
            ()
          };
          immutable.this.List.apply[Int](1,3).map[Char,List[Char]](scala.this.Predef.wrapString("somestring"))(immutable.this.List.canBuildFrom[Char])
        };
        {
          new $anon();
          ()
        }
      }
    }
  }
}

看起来它被转换为WrappedString,它有一个apply方法.这解释了它是如何工作的,但没有解释,WrappedString如何被接受到A =>类型的参数中. B(如scaladoc中所述).有人可以解释一下,请问这是怎么回事?

解决方法

通过collection.Seq [Char],它是PartialFunction [Int,Char]的子类型,它是Int =>的子类型.字符:

scala> implicitly[collection.immutable.WrappedString <:< (Int => Char)]
res0: <:<[scala.collection.immutable.WrappedString,Int => Char] = <function1>

因此,只有一个隐式转换发生 – 原始String => WrappedString,因为我们正在处理像函数一样的字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读