Reputation: 77
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
I'm confusing about the res2. I think the res2 should be '$anonfun$1.class'.
Upvotes: 2
Views: 121
Reputation: 170825
This one was fun.
scala> val a = ((x: Int) => x).getClass.getName
a: String = $anonfun$1
scala> a == "$anonfun$1"
res2: Boolean = false
Wait, what?
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)
So the name of the class is actually $line4.$read$$iw$$iw$$anonfun$1
, not $anonfun$1
. But why does Scala REPL print it like this? All executable Scala code must be inside a class, trait, or object definition. So when you enter a line in REPL which isn't, it gets wrapped inside an object
. And apparently when printing an answer, REPL suppresses anything which looks like part of this object's generated name, even if it isn't where it comes from:
scala> "a$$iw$$b"
res7: String = a$$b
And $line4.$read$
qualifies for this suppression, but $read$
by itself doesn't.
Upvotes: 5