2017-03-24 158 views
2
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令人困惑replaceFirst

回答

5

這一個很有趣。

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中輸入的行不是時,它會被包裝在object之內。而且很顯然,在打印的答案時,REPL抑制什麼,它看起來像此對象的生成的名稱的一部分,即使它不是來自何處:本身沒有按

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

$line4.$read$資格這種抑制,但$read$ 「T。