Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Generic Variables in Scala

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
}
like image 776
IttayD Avatar asked Oct 19 '09 20:10

IttayD


1 Answers

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
  }
like image 117
Mitch Blevins Avatar answered Oct 01 '22 17:10

Mitch Blevins