Scala - 在另一个范围内提供隐式值类

时间:2017-02-09 04:05:01

标签: scala implicit-conversion scoping

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

富/ FStream.scala

foo

富/ package.scala

package foo

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

酒吧/ usage.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 = ???
  }
} 

1 个答案:

答案 0 :(得分:5)

我建议您先阅读强制性tutorial

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

富/ 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
  }
}