为什么以下代码有效?
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,因为我们正在处理像函数一样的字符串.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。