[英]In Scala, define a generic tuple type with variable length and multiple types
我如何定义一个通用的元组类型,它可以
?
在下面的示例中,我需要在trait A
中定义foo
的返回类型以匹配子对象的实现。
trait A {
def foo: // how to define the return type here?
}
object O1 extends A {
def foo: (Int, String) = (123, "a string")
}
object O2 extends A {
def foo: ((String, Boolean), Int) = (("string inside a sub-tuple", true), 0, "another string")
}
由于这是Scala 2 ,因此您有两个选择。
仅使用香草Scala ,您可以这样做:
trait A {
type O <: Product
def foo: O
}
object O1 extends A {
override final type O = (Int, String)
override def foo: (Int, String) =
(123, "a string")
}
如果您从不想抽象A
,这可能会起作用,但如果您这样做,那么使用Product
是非常不愉快的。
如果您使用Shapeless ,这意味着您可以使用HList
而不是Product
,这将使具体实现的使用更加困难,但抽象的使用更加容易(但仍然很不愉快) 。
无论如何,我仍然建议您检查这是否真的是解决您的元问题的最佳解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.