gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:12:46 24 4
gpt4 key购买 nike

我有一个包裹foo其中包含类 FStreamfoo的包对象定义了一些隐式值类,为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 = ???
}
}

酒吧/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)
}

用法.scala

import foo.FStream

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

关于Scala – 使隐式值类在另一个范围内可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com