编写了一些scala工具后,我正试图掌握安排代码的最佳方法 - 特别是暗示.我有2个目标:
为了避免重复隐含,我提出了这种结构(类似于scalaz的排列方式):
case class StringW(s : String) {
def contrived = s + "?"
}
trait StringWImplicits {
implicit def To(s : String) = StringW(s)
implicit def From(sw : StringW) = sw.s
}
object StringW extends StringWImplicits
// Elsewhere on Monkey Island
object World extends StringWImplicits with ListWImplicits with MoreImplicits
Run Code Online (Sandbox Code Playgroud)
这让我只是
import StringW._ // Selective import
Run Code Online (Sandbox Code Playgroud)
或(在大多数情况下)
import World._. // Import everything
Run Code Online (Sandbox Code Playgroud)
其他人如何做到这一点?
我认为implicit如果你不知道转换来自哪里,那么转换是危险的。就我而言,我将我的implicits 放在一个Conversions类中,并尽可能import接近使用
def someMethod(d: Date) ; Unit {
import mydate.Conversions._
val tz = TimeZone.getDefault
val timeOfDay = d.getTimeOfDay(tz) //implicit used here
...
}
Run Code Online (Sandbox Code Playgroud)
我不确定我是否喜欢从各种 s 中“继承”隐式,因为同样的原因,实现 antrait被认为是不好的 Java 实践interface,因此您可以直接使用它的常量(首选静态导入)。