合成函数“##"在斯卡拉

编程入门 行业动态 更新时间:2024-10-11 15:23:58
本文介绍了合成函数“##"在斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近看到一些类似这样的代码:

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/

更多推荐

合成函数“##"在斯卡拉

本文发布于:2023-07-15 13:18:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   斯卡   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!