简体   繁体   English

在scala中使用enrich-my-library的最佳方法是什么?

[英]What is the best way to use enrich-my-library in scala?

The are two different way to implement it. 这是实现它的两种不同方式。

One is more short 一个更短

implicit def toR1(s:String) = new { def getLength = s.length)}

Second is more long 第二是更长

class R2(s:String){def getLength2 = s.length)}
implicit def toR2(s:String) = new R2(s)

Which one is better? 哪一个更好?

The first version uses a structural type . 第一个版本使用结构类型 It makes it possible to write short and readable code, but a disadvantage of structural types is that reflection is used at runtime when you call the method in the structural type. 它使编写简短且可读的代码成为可能,但结构类型的缺点是在结构类型中调用方法时在运行时使用反射。 Calling a method via reflection is slower than calling a method directly. 通过反射调用方法比直接调用方法要慢。

More details are in this blog post (written by me): Avoid structural types when pimping libraries 更多细节在这篇博客文章中(由我编写): 在拉皮条库时避免使用结构类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 丰富我的图书馆优化 - Enrich-My-Library optimization Enrich-My-Library适用于所有Traversables - Enrich-My-Library For all Traversables 如何将enrich-my-library模式应用于Scala集合? - How do I apply the enrich-my-library pattern to Scala collections? 使用enrich-my-library键入匿名函数的推断 - Type inference on anonymous functions with enrich-my-library 如何使用我自己的通用`map`(正确的方法)来丰富Scala集合? - How to enrich Scala collections with my own generic `map` (the right way)? 如何丰富具有静态方法的 Java 库类(也就是丰富 Scala 中的对象)? - How to enrich a Java library class that has static methods (aka enrich an object in Scala)? 使用Scala和SBT为可以从SBT CLI构建的库创建样本的最佳方法是什么? - What's the best way using Scala and SBT to create samples for a library that can be built from the SBT CLI? 有没有办法“丰富”Scala类而不将代码包装到另一个对象中? - Is there a way to “enrich” a Scala class without wrapping the code into another object? Scala:将元素追加到数组的最佳方法是什么? - Scala: what is the best way to append an element to an Array? 在Scala中格式化字符串的最佳方法是什么? - What is the best way to format a string in Scala?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM