gpt4 book ai didi

scala - scala ReplaceFirst 令人困惑

转载 作者:行者123 更新时间:2023-12-01 15:57:59 25 4
gpt4 key购买 nike

scala > val a = (x:Int)=>x+1
res0: Int => Int = <function1>
scala > val b = a.getClass
b: Class[_ <: Int => Int] = class $anonfun$1
scala > b.getName.replaceFirst("^.*\\.", "") + ".class"
//Why there is a prefix '$read$'
res2: String = $read$$anonfun$1.class

我对 res2 感到困惑。我认为 res2 应该是 '$anonfun$1.class'。

最佳答案

这个很有趣。

scala> val a = ((x: Int) => x).getClass.getName
a: String = $anonfun$1

scala> a == "$anonfun$1"
res2: Boolean = false

等等,什么?

scala> a.getBytes.map(_.toChar)
res3: Array[Char] = Array($, l, i, n, e, 4, ., $, r, e, a, d, $, $, i, w, $, $, i, w, $, $, a, n, o, n, f, u, n, $, 1)

所以类的名称实际上是$line4.$read$$iw$$iw$$anonfun$1,而不是$anonfun$1。但为什么 Scala REPL 会这样打印呢?所有可执行的 Scala 代码必须位于类、特征或对象定义内。因此,当您在 REPL 中输入一行但不是的行时,它会被包装在一个对象中。显然,在打印答案时,REPL 会抑制任何看起来像该对象生成名称一部分的内容,即使它不是它的来源:

scala> "a$$iw$$b"
res7: String = a$$b

并且 $line4.$read$ 符合此抑制条件,但 $read$ 本身不符合此抑制条件。

关于scala - scala ReplaceFirst 令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42991994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com