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

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

富/ FStream.scala

package foo

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

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

酒吧/ 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并获得所有的功能。 这也使用特质来分离文件。

富/ FStream.scala

package foo

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

// companion provides implicit
object FStream extends FStreamOp

富/ 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
  }
}
链接地址: http://www.djcxy.com/p/78959.html

上一篇: Scala – Make implicit value classes available in another scope

下一篇: Java vararg pass lambda and values