Initializing Generic Variables in Scala

ぃ、小莉子 提交于 2021-02-07 05:28:29

问题


How do I declare a generic variable in Scala without initializing it (or initializing to any value)?

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

回答1:


def foo[T] {
   var t: T = null.asInstanceOf[T]
   t
}

And, if you don't like the ceremony involved in that, you can ease it this way:

  // 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:


You can't not initialize local variables, but you can do so for fields:

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


来源:https://stackoverflow.com/questions/1590821/initializing-generic-variables-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!