Scala – 使隐式值类在另一个作用域中可用



我有一个包含类FStream的包foofoo 的包对象定义了一些隐式值类,这些类为FStream提供了扩展器方法。我想将这些值类移出包对象并移动到它们自己的单个文件中,但我也希望它们在使用FStream时始终可用(或者最好是,当我使用包中的任何内容时foo。有可能做到这一点吗?我尝试将隐式值类放入其他对象中,但无法从对象扩展。尝试将它们放在类或特征中,但隐式值类只能在其他对象中定义。

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

我建议您先阅读必修教程。

我的解决方案是使用 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
  }
}

最新更新