Initializing Generic Variables in Scala

前端 未结 2 1092

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条回答
  • 2021-02-20 07:45

    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 讨论(0)
  • 2021-02-20 07:47
    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
      }
    
    0 讨论(0)
提交回复
热议问题