Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: why does underscore (_) initialization work for fields but not method variables?

Tags:

scala

this works:

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

but this doesn't:

scala> def foo[T] = {
     |   var t: T = _
     | }
<console>:5: error: local variables must be initialized
         var t: T = _

why?

(one can use:

var t: T = null.asInstanceOf[T]

)

like image 905
IttayD Avatar asked Oct 21 '09 04:10

IttayD


1 Answers

This is defined in section 4.2 of the Scala Language Specification (my italics)

A variable definition var x: T = _ can appear only as a member of a template. It introduces a mutable field with type T and a default initial value

This, of course, does not answer the why this should be so!

like image 168
oxbow_lakes Avatar answered Sep 22 '22 17:09

oxbow_lakes