【问题标题】:Initializing Generic Variables in Scala在 Scala 中初始化泛型变量
【发布时间】:2009-10-19 20:08:58
【问题描述】:

如何在 Scala 中声明一个泛型变量而不初始化它(或初始化为任何值)?

def foo[T] {
   var t: T = ???? // tried _, null
   t
}

【问题讨论】:

    标签: scala variables initialization


    【解决方案1】:
    def foo[T] {
       var t: T = null.asInstanceOf[T]
       t
    }
    

    而且,如果您不喜欢其中涉及的仪式,您可以这样简化:

      // Import this into your scope
      case class Init()
      implicit def initToT[T](i: Init): T = {
        null.asInstanceOf[T]
      }
    
      // Then use it
      def foo[T] {
        var t: T = Init()
        t
      }
    

    【讨论】:

      【解决方案2】:

      你不能不初始化局部变量,但你可以对字段这样做:

      scala> class foo[T] {
           | var t: T = _
           | }
      defined class foo
      

      【讨论】:

      • 你知道为什么允许类变量而不是方法变量吗?
      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2019-03-16
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      相关资源
      最近更新 更多