Scala – 使隐式值 类 在另一个范围内可用

Scala – Make implicit value classes available in another scope

我有一个包 foo,其中包含 class FStreamfoo 的包对象定义了一些为 FStream 提供扩展方法的隐式值 classes。我想将这些值 classes 从包对象中移出并放入它们自己的单独文件中,但我也希望它们在我使用 FStream 时始终可用(或者最好是,当我使用任何东西时来自 foo 包。是否有可能完成此操作?我尝试将隐式值 classes 放入其他对象,但我无法从对象扩展。尝试将它们放入 classes 或traits,但隐式值classes只能在其他对象中定义。

foo/FStream.scala

package foo

class FStream {
  def makeFoo(): Unit = ???
}

foo/package.scala

package foo

package object foo {

  // I want to move these definitions into separate files:

  implicit class SuperFoo(val stream: FStream) extends AnyVal {
    def makeSuperFoo(): Unit = ???
  }

  implicit class HyperFoo(val stream: FStream) extends AnyVal {
    def makeHyperFoo(): Unit = ???
  }
} 

bar/usage.scala

package bar

import foo._ // something nice and short that doesn't reference individual value classes

val x: FStream = ???
x.makeSuperFoo() // should work
x.makeHyperFoo() // should work

我建议您先阅读必读内容 tutorial

我的解决方案是使用 FStream 的伴生对象。因此,您只需导入 FStream 即可获得所有功能。这也使用特征来分隔文件。

foo/FStream.scala

package foo

class FStream {
  def makeFoo(): Unit = ???
}

// companion provides implicit
object FStream extends FStreamOp

foo/FStreamOp.scala

package foo

// value class may not be a member of another class
class SuperFoo(val stream: FStream) extends AnyVal {
  def makeSuperFoo(): Unit = ???
}

class HyperFoo(val stream: FStream) extends AnyVal {
  def makeHyperFoo(): Unit = ???
}
trait FStreamOp {
  // you need to provide separate implicit conversion
  implicit def makeSuper(stream: FStream) = new SuperFoo(stream)
  implicit def makeHyper(stream: FStream) = new HyperFoo(stream)
}

usage.scala

import foo.FStream

object Main {
  def main(args: Array[String]): Unit = {
    val x: FStream = ???
    x.makeSuperFoo() // should work
    x.makeHyperFoo() // should work
  }
}