Default values for object fields

Object fields are allowed to have a constant default value. The type of field can be omitted if a default value is given.

  1. type
  2. Foo = object
  3. a: int = 2
  4. b: float = 3.14
  5. c = "I can have a default value"
  6. Bar = ref object
  7. a: int = 2
  8. b: float = 3.14
  9. c = "I can have a default value"

The explicit initialization uses these defaults which includes an object created with an object construction expression or the procedure default; a ref object created with an object construction expression or the procedure new; an array or a tuple with a subtype which has a default created with the procedure default.

  1. type
  2. Foo = object
  3. a: int = 2
  4. b = 3.0
  5. Bar = ref object
  6. a: int = 2
  7. b = 3.0
  8. block: # created with an object construction expression
  9. let x = Foo()
  10. assert x.a == 2 and x.b == 3.0
  11. let y = Bar()
  12. assert y.a == 2 and y.b == 3.0
  13. block: # created with an object construction expression
  14. let x = default(Foo)
  15. assert x.a == 2 and x.b == 3.0
  16. let y = default(array[1, Foo])
  17. assert y[0].a == 2 and y[0].b == 3.0
  18. let z = default(tuple[x: Foo])
  19. assert z.x.a == 2 and z.x.b == 3.0
  20. block: # created with the procedure `new`
  21. let y = new Bar
  22. assert y.a == 2 and y.b == 3.0