12

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
}

2 Answers 2

16
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
  }
Sign up to request clarification or add additional context in comments.

Comments

8

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

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

1 Comment

do you know why it is allowed for class variables but not method variables?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.