假设我有一个变量
val allF = (Some(1), "some string", 2.99, "another string", 1, Some(30))
现在我想声明几个与 allF
类型相同的变量,即 (Some[Int], String, Double, String, Int, Some[Int])
。我能做到
var a1: (Some[Int], String, Double, String, Int, Some[Int]) = _
var a2: (Some[Int], String, Double, String, Int, Some[Int]) = _
... and so on
或者我可以做
type T = (Some[Int], String, Double, String, Int, Some[Int])
var a1: T = _
var a2: T = _
.. and do on
有什么方法可以使用变量allF
来获取其类型并声明变量a1
,a2
,a3
,...像这样
val allF = (Some(1), "some string", 2.99, "another string", 1, Some(30))
var a1: typeof(allF) = _
var a2: typeof(allF) = _
...
更新- 也适用于这样的情况
val allF = (Some(1), "some string", 2.99, "another string", 1, Some(30))
xyz match {
case y: (???)\\ if y is of the same type as allF
}
最佳答案
这取决于你的意思。
如果您确实想在同一范围内声明所有变量,按照您的示例,您可以这样做:
var a, b, c = (5,4,3,2,1) // All have the same type and value
但是,如果您说要创建一个与编译时不知道其类型的变量具有相同类型的变量(可能是作为参数传递的 AnyRef
),那么您将受到与 Java(或任何其他静态类型语言)中相同的限制。您可以通过反射创建变量,但只能将其作为对象进行操作。
关于scala - 在 Scala 中声明一个与另一个变量类型相同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878014/