我有
trait Foo:
def foo: Int
trait Bar:
def bar: Int
given Foo with
def foo = 1
given Bar with
def bar = 1
我有一個功能 foobar
type FooBar = Foo & Bar
def foobar(using FooBar) = ...
A & B如果我已經給定了 A 和 B,那么為型別創建給定的最簡單方法是什么
uj5u.com熱心網友回復:
你可以得到Foo & Bar通過嵌套using子句中的given實體,但一旦你開始修改的值FooBar的結果可能不是你所期望的,因為FooBar也是Foo和Bar和東西開始變得遞回:
trait FooBar extends Foo with Bar
given (using f: Foo, b: Bar): FooBar with
def foo = f.foo 1
def bar = b.bar 2
def fooBar(using fb: Foo & Bar) = (fb.foo, fb.bar)
def foo(using f: Foo) = f.foo
def bar(using b: Bar) = b.bar
@main def main() =
println(foo) //2
println(bar) //3
println(fooBar) //(3, 5)
IMO 你應該避免與型別類的子型別關系,并在FooBar不擴展Foo和的情況下定義Bar:
trait FooBar:
def foo: Int
def bar: Int
given (using f: Foo, b: Bar): FooBar with
def foo = f.foo 1
def bar = b.bar 2
uj5u.com熱心網友回復:
誠然,我沒有直接的 Scala 3 經驗,但最簡單的解決方案將歸結為:
given aAndB(using a: A, b: B): A & B with {
def foo: Int = a.foo
def bar: Int = b.bar
}
您正在有效地將 A 和 B 粘合在一起并進行適當的調度。
有可能實作一個宏來自動調度(當沒有沖突時)。
AFAICT,這相當于 Scala 2:
implicit def aAndB(implicit a: A, b: B) = new A with B {
def foo: Int = a.foo
def bar: Int = b.bar
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/393575.html
上一篇:使用navArgs將Fragment轉換為DialogFragment,如何從Fragment類外部導航到DialogFragment
