在Scala中声明一个变量,其类型与另一个变量相同

时间:2015-04-26 13:06:32

标签: scala

假设我有一个变量

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来获取其类型并声明变量a1a2a3,...就像这样

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
}

4 个答案:

答案 0 :(得分:1)

这取决于你的意思。

如果您真的想要在同一范围内声明所有变量,根据您的示例,您可以这样做:

  var a, b, c = (5,4,3,2,1) // All have the same type and value

但是如果你想创建一个与变量类型相同的变量,那么在编译时你不知道它的类型(可能是作为参数传递的AnyRef),那么你就是受到与Java(或任何其他静态类型语言)相同的限制。您可以通过反射创建变量,但只能将其作为对象进行操作。

答案 1 :(得分:1)

我理解的问题是,是否有一个方便的编译器指令来定义变量 b 的类型与变量 a 的推断类型相同。如果这是正确的理解,那么我认为答案是否定的。

可以显式地命名类型,或者在编译时推断出类型,但是不可能通过引用为不同变量推断的类型来定义变量。 Scala没有任何语言结构可以做到这一点。 (我实际上并不知道任何支持此语言的语言。)

可以通过简单地将 a 的值分配给 b ,然后重新分配 b 具有正确的价值。但最好只显式定义类型并按名称引用它 - 如果这是一个问题,代码几乎肯定会在长期内更易于维护。如果 a b 是val,那么这个分配技巧显然不起作用。

答案 2 :(得分:0)

你绝对可以按照你提出的第二种方式进行。要解决有关案例匹配的更新,您可以执行以下操作:

  object MyTypes {
    type F = (Some[Int], String, Double, String, Int, Some[Int])
    type G = (Some[Int], Long, Double, Long, Int, Some[Int])

  }
  val allF: MyTypes.F  = (Some(1), "some string", 2.99, "another string", 1, Some(30))
  val allG: MyTypes.G = (Some(1), 101, 2.99, 9999999, 1, Some(30))


  import scala.reflect.runtime.universe._ //This allows typeOf[] and etc
  val tuple = allF
  typeOf[tuple.type] match {
    case fType if fType =:= typeOf[MyTypes.F] => "do something 1"
    case gType if gType =:= typeOf[MyTypes.G] => "do something 2"
  }

那或者你只是做一些更标准的东西,而不是类型系统中那么先进:

  val allF = (Some(1), "some string", 2.99, "another string", 1, Some(30))
  val allG = (Some(1), 101, 2.99, 9999999, 1, Some(30))

  val tuple: (_, _, _, _, _, _) = allF
  tuple match {
    case (x1: Some[Int], x2: String, x3: Double, x4: String, x5: Int, x6: Some[Int]) => "do something 1"
    case (x1: Some[Int], x2: Long, x3: Double, x4: Long, x5: Int, x6: Some[Int]) => "do something 2"
    case _ => "Handle not found"
  }

答案 3 :(得分:0)

如果你想要相同ref类型的默认值,只需定义一个乐趣并按如下方式使用它:

th:href