开发者

Initializing Generic Variables in Scala

开发者 https://www.devze.com 2022-12-09 11:42 出处:网络
How do I declare a generic variable in Scala without initializing it (or initializing to any value)?

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

def foo[T] {
   var t: T =开发者_JAVA百科 ???? // tried _, null
   t
}


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
  }


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号