object test extends App {
implicit class f(i: Int) { println("!!!"); def f = 42 + i }
1.f
2.f
3.f
}
在.class文件中我们看到
public static test$f f(int);
Code:
0: getstatic #16 // Field test$.MODULE$:Ltest$;
3: iload_0
4: invokevirtual #42 // Method test$.f:(I)Ltest$f;
7: areturn
所以,看起来有一个静态方法,但是这段代码打印出“!!!”运行时3次。每个隐式类转换是否都有新的类实例化?如果是,为什么?如果不是,为什么“!!!”打印了三次?
最佳答案
您可以通过将其设为 value class 来避免实例化您的扩展类
implicit class f(val i: Int) extends AnyVal { def f = 42 + i }
请注意,您不能将 println
放入其中,但这里引用了上面链接的文档:
At runtime, this expression 3.toHexString is optimised to the equivalent of a method call on a static object (RichInt$.MODULE$.extension$toHexString(3)), rather than a method call on a newly instantiated object.
关于scala - 是否为每个隐式类转换创建类的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454260/