在 Scala 中使用丰富我的图书馆的最佳方法是什么? [英] What is the best way to use enrich-my-library in scala?

查看:52
本文介绍了在 Scala 中使用丰富我的图书馆的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种不同的实现方式.

The are two different way to implement it.

一个更短

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

第二个更长

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

哪个更好?

推荐答案

第一个版本使用 结构类型.它使编写简短易读的代码成为可能,但结构类型的一个缺点是在运行时调用结构类型中的方法时会使用反射.通过反射调用方法比直接调用方法慢.

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

这篇关于在 Scala 中使用丰富我的图书馆的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆