我最近看到一些类似这样的代码:
I recently saw some code like this code:
val x: Any = "a" val y = x.## // y: Int = 97好吧,输出只是'a'的ASCI值,但让我们看看
Well, ok the output is just the ASCI value of 'a', but lets have a look at
List(1,2).## // Int = 985731359 List(1,2).toString.## // Int = 1063384434我的 IDE 告诉##"它是一个合成函数".那么## 在做什么,什么是合成函数?
My IDE tells about '##' that it is a 'Synthetic Function'. So what is ## doing and what is a Synthetic Function?
推荐答案它基本上是 hashCode 的别名,但有几个值得注意的例外,使其更安全:
It's basically an alias of hashCode, with a couple of notable exceptions that make it somewhat safer:
等价于 x.hashCode,但盒装数字类型和 null 除外.对于数字,它返回一个与值相等一致的哈希值:如果两个值类型实例比较为真,那么 ## 将为它们中的每一个生成相同的哈希值.对于 null 返回一个哈希码,其中 null.hashCode 抛出一个 NullPointerException.
Equivalent to x.hashCode except for boxed numeric types and null. For numerics, it returns a hash value which is consistent with value equality: if two value type instances compare as true, then ## will produce the same hash value for each of them. For null returns a hashcode where null.hashCode throws a NullPointerException.
(来源:www.scala-lang/api/current/scala/Any.html###:Int)
示例:
正常值
scala> val x: Any = "a" x: Any = a scala> x.hashCode res2: Int = 97 scala> x.## res3: Int = 97空值
scala> null.hashCode java.lang.NullPointerException ... 33 elided scala> null.## res5: Int = 0相反,合成字段是由编译器生成的字段,用于解决底层 JVM 限制,尤其是在处理内部匿名类时,这是一个与 JVM 无关的概念.
A synthetic field, instead, is a field generated by the compiler to work around the underlying JVM limitations, especially when dealing with inner anonymous classes, a concept extraneous to the JVM.
这里有一个很好的解释它的详细含义:javapapers/core-java/java-synthetic-class-method-field/
Here's a good explanation of what it means in details: javapapers/core-java/java-synthetic-class-method-field/
更多推荐
合成函数“##"在斯卡拉
发布评论