gpt4 book ai didi

java - Scala 只接受 List 中的 String 或 Int 通用案例类

转载 作者:行者123 更新时间:2023-12-05 05:13:58 25 4
gpt4 key购买 nike

我有一个定义如下的案例类

case class ChooseBoxData[T](index:T, text:String)

是否可以声明一个列表,使列表只接受 ChooseBoxData[String] 和 ChooseBoxData[Int] 类型?

我期望的是这样的:

val specialList:List[some type declaration] = List(
ChooseBoxData[String]("some string","some string"),/* allow, because is ChooseBoxData[String]*/
ChooseBoxData[Int](12,"some string"), /* also allow, because is ChooseBoxData[Int]*/
ChooseBoxData[Boolean](true,"some string")/* not allow type other than ChooseBoxData[String] or ChooseBoxData[Int]*/
)

最佳答案

可能是这样的:

trait AllowableBoxData  
object AllowableBoxData {
private of[T](cbd: ChooseBoxData[T]) = new ChooseBoxData(cbd.index, cbd.text)
with AllowableBoxData
implicit def ofInt(cbd: ChooseBoxData[Int]) = of(cbd)
implicit def ofString(cbd: ChooseBoxData[String]) = of(cbd)
}

现在你可以做类似的事情了

val list: List[ChooseBoxData[_] with AllowableBoxData] = List(ChooseBoxData("foo", "bar"), ChooseBoxData(0, "baz")

但不是 val list: List[AllowableBoxData] = List(ChooseBoxData(false, "baz"))

此外,如果您希望声明一个函数参数而不仅仅是一个变量,那么会有更优雅的解决方案:

trait CanUse[T]
implicit case object CanUseInt extends CanUse[Int]
implicit case object CanUseString extends CanUse[String]

def foo[T : CanUse](bar: List[ChooseBoxData[T]])

关于java - Scala 只接受 List 中的 String 或 Int 通用案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029019/

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