blob: 926638bad5c81bd49e5bcdf0f1c34c4682c525e3 [file] [log] [blame]
Bram Moolenaar71badf92023-04-22 22:40:14 +01001*vim9class.txt* For Vim version 9.0. Last change: 2023 Mar 22
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00007NOTE - This is not finished yet, anything can still change! - NOTE
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00008
9
10Vim9 classes, objects, interfaces, types and enums.
11
121. Overview |Vim9-class-overview|
132. A simple class |Vim9-simple-class|
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000143. Class members and functions |Vim9-class-member|
154. Using an abstract class |Vim9-abstract-class|
165. Using an interface |Vim9-using-interface|
176. More class details |Vim9-class|
187. Type definition |Vim9-type|
198. Enum |Vim9-enum|
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000020
219. Rationale
2210. To be done later
23
24==============================================================================
25
261. Overview *Vim9-class-overview*
27
28The fancy term is "object-oriented programming". You can find lots of study
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000029material on this subject. Here we document what |Vim9| script provides,
30assuming you know the basics already. Added are helpful hints about how to
31use this functionality effectively.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000032
33The basic item is an object:
34- An object stores state. It contains one or more variables that can each
35 have a value.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000036- An object provides functions that use and manipulate its state. These
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000037 functions are invoked "on the object", which is what sets it apart from the
38 traditional separation of data and code that manipulates the data.
39- An object has a well defined interface, with typed member variables and
40 member functions.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000041- Objects are created from a class and all objects have the same interface.
42 This does not change at runtime, it is not dynamic.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000043
44An object can only be created by a class. A class provides:
45- A new() method, the constructor, which returns an object for the class.
46 This method is invoked on the class name: MyClass.new().
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000047- State shared by all objects of the class: class variables (class members).
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000048- A hierarchy of classes, with super-classes and sub-classes, inheritance.
49
50An interface is used to specify properties of an object:
51- An object can declare several interfaces that it implements.
52- Different objects implementing the same interface can be used the same way.
53
54The class hierarchy allows for single inheritance. Otherwise interfaces are
55to be used where needed.
56
57
58Class modeling ~
59
60You can model classes any way you like. Keep in mind what you are building,
61don't try to model the real world. This can be confusing, especially because
62teachers use real-world objects to explain class relations and you might think
63your model should therefore reflect the real world. It doesn't! The model
64should match your purpose.
65
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000066Keep in mind that composition (an object contains other objects) is often
67better than inheritance (an object extends another object). Don't waste time
68trying to find the optimal class model. Or waste time discussing whether a
69square is a rectangle or that a rectangle is a square. It doesn't matter.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000070
71
72==============================================================================
73
742. A simple class *Vim9-simple-class*
75
Bram Moolenaarbe4e0162023-02-02 13:59:48 +000076Let's start with a simple example: a class that stores a text position (see
77below for how to do this more efficiently): >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +000078
79 class TextPosition
80 this.lnum: number
81 this.col: number
82
83 def new(lnum: number, col: number)
84 this.lnum = lnum
85 this.col = col
86 enddef
87
88 def SetLnum(lnum: number)
89 this.lnum = lnum
90 enddef
91
92 def SetCol(col: number)
93 this.col = col
94 enddef
95
96 def SetPosition(lnum: number, col: number)
97 this.lnum = lnum
98 this.col = col
99 enddef
100 endclass
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000101< *object* *Object*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000102You can create an object from this class with the new() method: >
103
104 var pos = TextPosition.new(1, 1)
105
106The object members "lnum" and "col" can be accessed directly: >
107
108 echo $'The text position is ({pos.lnum}, {pos.col})'
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000109< *E1317* *E1327*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000110If you have been using other object-oriented languages you will notice that
111in Vim the object members are consistently referred to with the "this."
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000112prefix. This is different from languages like Java and TypeScript. The
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000113naming convention makes the object members easy to spot. Also, when a
114variable does not have the "this." prefix you know it is not an object member.
115
116
117Member write access ~
118
119Now try to change an object member directly: >
120
121 pos.lnum = 9
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000122< *E1335*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000123This will give you an error! That is because by default object members can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000124read but not set. That's why the TextPosition class provides a method for it: >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000125
126 pos.SetLnum(9)
127
128Allowing to read but not set an object member is the most common and safest
129way. Most often there is no problem using a value, while setting a value may
130have side effects that need to be taken care of. In this case, the SetLnum()
131method could check if the line number is valid and either give an error or use
132the closest valid value.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000133 *:public* *E1331*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000134If you don't care about side effects and want to allow the object member to be
135changed at any time, you can make it public: >
136
137 public this.lnum: number
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000138 public this.col: number
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000139
140Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting
141"pos.lnum" directly above will no longer give an error.
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000142 *E1334*
143If you try to set an object member that doesn't exist you get an error: >
144 pos.other = 9
145< E1334: Object member not found: other ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000146
147
148Private members ~
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000149 *E1332* *E1333*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000150On the other hand, if you do not want the object members to be read directly,
151you can make them private. This is done by prefixing an underscore to the
152name: >
153
154 this._lnum: number
155 this._col number
156
157Now you need to provide methods to get the value of the private members.
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000158These are commonly called getters. We recommend using a name that starts with
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000159"Get": >
160
161 def GetLnum(): number
162 return this._lnum
163 enddef
164
165 def GetCol() number
166 return this._col
167 enddef
168
169This example isn't very useful, the members might as well have been public.
170It does become useful if you check the value. For example, restrict the line
171number to the total number of lines: >
172
173 def GetLnum(): number
174 if this._lnum > this._lineCount
175 return this._lineCount
176 endif
177 return this._lnum
178 enddef
179
180
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200181Private methods ~
182If you want object methods to be accessible only from other methods of the
183same class and not used from outside the class, then you can make them
184private. This is done by prefixing the method name with an underscore: >
185
186 class SomeClass
187 def _Foo(): number
188 return 10
189 enddef
190 def Bar(): number
191 return this._Foo()
192 enddef
193 endclass
194<
195Accessing a private method outside the class will result in an error (using
196the above class): >
197
198 var a = SomeClass.new()
199 a._Foo()
200<
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000201Simplifying the new() method ~
202
203Many constructors take values for the object members. Thus you very often see
204this pattern: >
205
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000206 class SomeClass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000207 this.lnum: number
208 this.col: number
209
210 def new(lnum: number, col: number)
211 this.lnum = lnum
212 this.col = col
213 enddef
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000214 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000215
216Not only is this text you need to write, it also has the type of each member
217twice. Since this is so common a shorter way to write new() is provided: >
218
219 def new(this.lnum, this.col)
220 enddef
221
222The semantics are easy to understand: Providing the object member name,
223including "this.", as the argument to new() means the value provided in the
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000224new() call is assigned to that object member. This mechanism comes from the
225Dart language.
226
227Putting together this way of using new() and making the members public results
Bram Moolenaar71badf92023-04-22 22:40:14 +0100228in a much shorter class definition than what we started with: >
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000229
230 class TextPosition
231 public this.lnum: number
232 public this.col: number
233
234 def new(this.lnum, this.col)
235 enddef
236
237 def SetPosition(lnum: number, col: number)
238 this.lnum = lnum
239 this.col = col
240 enddef
241 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000242
243The sequence of constructing a new object is:
2441. Memory is allocated and cleared. All values are zero/false/empty.
2452. For each declared member that has an initializer, the expression is
246 evaluated and assigned to the member. This happens in the sequence the
247 members are declared in the class.
2483. Arguments in the new() method in the "this.name" form are assigned.
2494. The body of the new() method is executed.
250
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000251If the class extends a parent class, the same thing happens. In the second
252step the members of the parent class are done first. There is no need to call
253"super()" or "new()" on the parent.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000254
Yegappan Lakshmanan6ac15442023-08-20 18:20:17 +0200255When defining the new() method the return type should not be specified. It
256always returns an object of the class.
257
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000258==============================================================================
259
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00002603. class members and functions *Vim9-class-member*
261
262 *:static* *E1337* *E1338*
263Class members are declared with "static". They are used by the name without a
264prefix: >
265
266 class OtherThing
267 this.size: number
268 static totalSize: number
269
270 def new(this.size)
271 totalSize += this.size
272 enddef
273 endclass
274< *E1340* *E1341*
275Since the name is used as-is, shadowing the name by a function argument name
276or local variable name is not allowed.
277
278Just like object members the access can be made private by using an underscore
279as the first character in the name, and it can be made public by prefixing
280"public": >
281
282 class OtherThing
283 static total: number # anybody can read, only class can write
284 static _sum: number # only class can read and write
285 public static result: number # anybody can read and write
286 endclass
287<
288 *class-function*
289Class functions are also declared with "static". They have no access to
290object members, they cannot use the "this" keyword. >
291
292 class OtherThing
293 this.size: number
294 static totalSize: number
295
296 # Clear the total size and return the value it had before.
297 static def ClearTotalSize(): number
298 var prev = totalSize
299 totalSize = 0
300 return prev
301 enddef
302 endclass
303
304Inside the class the function can be called by name directly, outside the
305class the class name must be prefixed: `OtherThing.ClearTotalSize()`.
306
Yegappan Lakshmanancd7293b2023-08-27 19:18:23 +0200307Just like object methods the access can be made private by using an underscore
308as the first character in the method name: >
309
310 class OtherThing
311 static def _Foo()
312 echo "Foo"
313 enddef
314 def Bar()
315 OtherThing._Foo()
316 enddef
317 endclass
318
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000319==============================================================================
320
3214. Using an abstract class *Vim9-abstract-class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000322
323An abstract class forms the base for at least one sub-class. In the class
324model one often finds that a few classes have the same properties that can be
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000325shared, but a class with these properties does not have enough state to create
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000326an object from. A sub-class must extend the abstract class and add the
327missing state and/or methods before it can be used to create objects for.
328
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000329For example, a Shape class could store a color and thickness. You cannot
330create a Shape object, it is missing the information about what kind of shape
331it is. The Shape class functions as the base for a Square and a Triangle
332class, for which objects can be created. Example: >
333
334 abstract class Shape
335 this.color = Color.Black
336 this.thickness = 10
337 endclass
338
339 class Square extends Shape
340 this.size: number
341
342 def new(this.size)
343 enddef
344 endclass
345
346 class Triangle extends Shape
347 this.base: number
348 this.height: number
349
350 def new(this.base, this.height)
351 enddef
352 endclass
353<
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000354An abstract class is defined the same way as a normal class, except that it
355does not have any new() method. *E1359*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000356
357
358==============================================================================
359
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00003605. Using an interface *Vim9-using-interface*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000361
362The example above with Shape, Square and Triangle can be made more useful if
363we add a method to compute the surface of the object. For that we create the
364interface called HasSurface, which specifies one method Surface() that returns
365a number. This example extends the one above: >
366
367 abstract class Shape
368 this.color = Color.Black
369 this.thickness = 10
370 endclass
371
372 interface HasSurface
373 def Surface(): number
374 endinterface
375
376 class Square extends Shape implements HasSurface
377 this.size: number
378
379 def new(this.size)
380 enddef
381
382 def Surface(): number
383 return this.size * this.size
384 enddef
385 endclass
386
387 class Triangle extends Shape implements HasSurface
388 this.base: number
389 this.height: number
390
391 def new(this.base, this.height)
392 enddef
393
394 def Surface(): number
395 return this.base * this.height / 2
396 enddef
397 endclass
398
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000399If a class declares to implement an interface, all the items specified in the
400interface must appear in the class, with the same types. *E1348* *E1349*
401
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000402The interface name can be used as a type: >
403
404 var shapes: list<HasSurface> = [
405 Square.new(12),
406 Triangle.new(8, 15),
407 ]
408 for shape in shapes
409 echo $'the surface is {shape.Surface()}'
410 endfor
411
412
413==============================================================================
414
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00004156. More class details *Vim9-class* *Class* *class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000416
417Defining a class ~
418 *:class* *:endclass* *:abstract*
419A class is defined between `:class` and `:endclass`. The whole class is
420defined in one script file. It is not possible to add to a class later.
421
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000422A class can only be defined in a |Vim9| script file. *E1316*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000423A class cannot be defined inside a function.
424
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000425It is possible to define more than one class in a script file. Although it
426usually is better to export only one main class. It can be useful to define
427types, enums and helper classes though.
428
429The `:abstract` keyword may be prefixed and `:export` may be used. That gives
430these variants: >
431
432 class ClassName
433 endclass
434
435 export class ClassName
436 endclass
437
438 abstract class ClassName
439 endclass
440
441 export abstract class ClassName
442 endclass
443<
444 *E1314*
445The class name should be CamelCased. It must start with an uppercase letter.
446That avoids clashing with builtin types.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000447 *E1315*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000448After the class name these optional items can be used. Each can appear only
449once. They can appear in any order, although this order is recommended: >
450 extends ClassName
451 implements InterfaceName, OtherInterface
452 specifies SomeInterface
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000453< *E1355*
454Each member and function name can be used only once. It is not possible to
455define a function with the same name and different type of arguments.
456
457
Yegappan Lakshmanan618e47d2023-08-22 21:29:28 +0200458Member Initialization ~
459If the type of a member is not explicitly specified in a class, then it is set
460to "any" during class definition. When an object is instantiated from the
461class, then the type of the member is set.
462
463
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000464Extending a class ~
465 *extends*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000466A class can extend one other class. *E1352* *E1353* *E1354*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000467The basic idea is to build on top of an existing class, add properties to it.
468
469The extended class is called the "base class" or "super class". The new class
470is called the "child class".
471
472Object members from the base class are all taken over by the child class. It
473is not possible to override them (unlike some other languages).
474
475 *E1356* *E1357* *E1358*
476Object methods of the base class can be overruled. The signature (arguments,
477argument types and return type) must be exactly the same. The method of the
478base class can be called by prefixing "super.".
479
480Other object methods of the base class are taken over by the child class.
481
482Class functions, including functions starting with "new", can be overruled,
483like with object methods. The function on the base class can be called by
484prefixing the name of the class (for class functions) or "super.".
485
486Unlike other languages, the constructor of the base class does not need to be
487invoked. In fact, it cannot be invoked. If some initialization from the base
488class also needs to be done in a child class, put it in an object method and
489call that method from every constructor().
490
491If the base class did not specify a new() function then one was automatically
492created. This function will not be taken over by the child class. The child
493class can define its own new() function, or, if there isn't one, a new()
494function will be added automatically.
495
496
497A class implementing an interface ~
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000498 *implements* *E1346* *E1347*
499A class can implement one or more interfaces. The "implements" keyword can
500only appear once *E1350* . Multiple interfaces can be specified, separated by
501commas. Each interface name can appear only once. *E1351*
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000502
503
504A class defining an interface ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000505 *specifies*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000506A class can declare its interface, the object members and methods, with a
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000507named interface. This avoids the need for separately specifying the
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000508interface, which is often done in many languages, especially Java.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000509
510
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000511Items in a class ~
512 *E1318* *E1325* *E1326*
Bram Moolenaardd60c362023-02-27 15:49:53 +0000513Inside a class, in between `:class` and `:endclass`, these items can appear:
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000514- An object member declaration: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000515 this._memberName: memberType
516 this.memberName: memberType
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000517 public this.memberName: memberType
518- A constructor method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000519 def new(arguments)
520 def newName(arguments)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000521- An object method: >
Bram Moolenaar938ae282023-02-20 20:44:55 +0000522 def SomeMethod(arguments)
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000523< *E1329*
524For the object member the type must be specified. The best way is to do this
525explicitly with ": {type}". For simple types you can also use an initializer,
526such as "= 123", and Vim will see that the type is a number. Avoid doing this
527for more complex types and when the type will be incomplete. For example: >
528 this.nameList = []
529This specifies a list, but the item type is unknown. Better use: >
530 this.nameList: list<string>
531The initialization isn't needed, the list is empty by default.
532 *E1330*
533Some types cannot be used, such as "void", "null" and "v:none".
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000534
535
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000536Defining an interface ~
537 *:interface* *:endinterface*
538An interface is defined between `:interface` and `:endinterface`. It may be
539prefixed with `:export`: >
540
541 interface InterfaceName
542 endinterface
543
544 export interface InterfaceName
545 endinterface
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000546< *E1344*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000547An interface can declare object members, just like in a class but without any
548initializer.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000549 *E1345*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000550An interface can declare methods with `:def`, including the arguments and
551return type, but without the body and without `:enddef`. Example: >
552
553 interface HasSurface
554 this.size: number
555 def Surface(): number
556 endinterface
557
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000558An interface name must start with an uppercase letter. *E1343*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000559The "Has" prefix can be used to make it easier to guess this is an interface
560name, with a hint about what it provides.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000561An interface can only be defined in a |Vim9| script file. *E1342*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000562
563
Bram Moolenaar938ae282023-02-20 20:44:55 +0000564null object ~
565
Bram Moolenaardd60c362023-02-27 15:49:53 +0000566When a variable is declared to have the type of an object, but it is not
Bram Moolenaar938ae282023-02-20 20:44:55 +0000567initialized, the value is null. When trying to use this null object Vim often
568does not know what class was supposed to be used. Vim then cannot check if
569a member name is correct and you will get an "Using a null object" error,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100570even when the member name is invalid. *E1360* *E1362* *E1363*
Bram Moolenaar938ae282023-02-20 20:44:55 +0000571
572
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000573Default constructor ~
574
575In case you define a class without a new() method, one will be automatically
576defined. This default constructor will have arguments for all the object
577members, in the order they were specified. Thus if your class looks like: >
578
579 class AutoNew
580 this.name: string
581 this.age: number
582 this.gender: Gender
583 endclass
584
585Then The default constructor will be: >
586
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000587 def new(this.name = v:none, this.age = v:none, this.gender = v:none)
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000588 enddef
589
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000590The "= v:none" default values make the arguments optional. Thus you can also
591call `new()` without any arguments. No assignment will happen and the default
592value for the object members will be used. This is a more useful example,
593with default values: >
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000594
595 class TextPosition
596 this.lnum: number = 1
597 this.col: number = 1
598 endclass
599
600If you want the constructor to have mandatory arguments, you need to write it
601yourself. For example, if for the AutoNew class above you insist on getting
602the name, you can define the constructor like this: >
603
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000604 def new(this.name, this.age = v:none, this.gender = v:none)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000605 enddef
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000606< *E1328*
607Note that you cannot use another default value than "v:none" here. If you
608want to initialize the object members, do it where they are declared. This
609way you only need to look in one place for the default values.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000610
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000611All object members will be used in the default constructor, also private
612access ones.
613
614If the class extends another one, the object members of that class will come
615first.
616
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000617
618Multiple constructors ~
619
620Normally a class has just one new() constructor. In case you find that the
621constructor is often called with the same arguments you may want to simplify
622your code by putting those arguments into a second constructor method. For
623example, if you tend to use the color black a lot: >
624
625 def new(this.garment, this.color, this.size)
626 enddef
627 ...
628 var pants = new(Garment.pants, Color.black, "XL")
629 var shirt = new(Garment.shirt, Color.black, "XL")
630 var shoes = new(Garment.shoes, Color.black, "45")
631
632Instead of repeating the color every time you can add a constructor that
633includes it: >
634
635 def newBlack(this.garment, this.size)
636 this.color = Color.black
637 enddef
638 ...
639 var pants = newBlack(Garment.pants, "XL")
640 var shirt = newBlack(Garment.shirt, "XL")
641 var shoes = newBlack(Garment.shoes, "9.5")
642
643Note that the method name must start with "new". If there is no method called
644"new()" then the default constructor is added, even though there are other
645constructor methods.
646
647
648==============================================================================
649
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00006507. Type definition *Vim9-type* *:type*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000651
652A type definition is giving a name to a type specification. For Example: >
653
654 :type ListOfStrings list<string>
655
656TODO: more explanation
657
658
659==============================================================================
660
Bram Moolenaarbe4e0162023-02-02 13:59:48 +00006618. Enum *Vim9-enum* *:enum* *:endenum*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000662
663An enum is a type that can have one of a list of values. Example: >
664
665 :enum Color
666 White
667 Red
668 Green
669 Blue
670 Black
671 :endenum
672
673TODO: more explanation
674
675
676==============================================================================
677
6789. Rationale
679
680Most of the choices for |Vim9| classes come from popular and recently
681developed languages, such as Java, TypeScript and Dart. The syntax has been
682made to fit with the way Vim script works, such as using `endclass` instead of
683using curly braces around the whole class.
684
685Some common constructs of object-oriented languages were chosen very long ago
686when this kind of programming was still new, and later found to be
687sub-optimal. By this time those constructs were widely used and changing them
688was not an option. In Vim we do have the freedom to make different choices,
689since classes are completely new. We can make the syntax simpler and more
690consistent than what "old" languages use. Without diverting too much, it
691should still mostly look like what you know from existing languages.
692
693Some recently developed languages add all kinds of fancy features that we
694don't need for Vim. But some have nice ideas that we do want to use.
695Thus we end up with a base of what is common in popular languages, dropping
696what looks like a bad idea, and adding some nice features that are easy to
697understand.
698
699The main rules we use to make decisions:
700- Keep it simple.
701- No surprises, mostly do what other languages are doing.
702- Avoid mistakes from the past.
703- Avoid the need for the script writer to consult the help to understand how
704 things work, most things should be obvious.
705- Keep it consistent.
706- Aim at an average size plugin, not at a huge project.
707
708
709Using new() for the constructor ~
710
711Many languages use the class name for the constructor method. A disadvantage
712is that quite often this is a long name. And when changing the class name all
713constructor methods need to be renamed. Not a big deal, but still a
714disadvantage.
715
716Other languages, such as TypeScript, use a specific name, such as
717"constructor()". That seems better. However, using "new" or "new()" to
718create a new object has no obvious relation with "constructor()".
719
720For |Vim9| script using the same method name for all constructors seemed like
721the right choice, and by calling it new() the relation between the caller and
722the method being called is obvious.
723
724
725No overloading of the constructor ~
726
727In Vim script, both legacy and |Vim9| script, there is no overloading of
728functions. That means it is not possible to use the same function name with
729different types of arguments. Therefore there also is only one new()
730constructor.
731
732With |Vim9| script it would be possible to support overloading, since
733arguments are typed. However, this gets complicated very quickly. Looking at
734a new() call one has to inspect the types of the arguments to know which of
735several new() methods is actually being called. And that can require
736inspecting quite a bit of code. For example, if one of the arguments is the
737return value of a method, you need to find that method to see what type it is
738returning.
739
740Instead, every constructor has to have a different name, starting with "new".
741That way multiple constructors with different arguments are possible, while it
742is very easy to see which constructor is being used. And the type of
743arguments can be properly checked.
744
745
746No overloading of methods ~
747
748Same reasoning as for the constructor: It is often not obvious what type
749arguments have, which would make it difficult to figure out what method is
750actually being called. Better just give the methods a different name, then
751type checking will make sure it works as you intended. This rules out
752polymorphism, which we don't really need anyway.
753
754
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000755Single inheritance and interfaces ~
756
757Some languages support multiple inheritance. Although that can be useful in
758some cases, it makes the rules of how a class works quite complicated.
759Instead, using interfaces to declare what is supported is much simpler. The
760very popular Java language does it this way, and it should be good enough for
Bram Moolenaarbe4e0162023-02-02 13:59:48 +0000761Vim. The "keep it simple" rule applies here.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000762
763Explicitly declaring that a class supports an interface makes it easy to see
764what a class is intended for. It also makes it possible to do proper type
765checking. When an interface is changed any class that declares to implement
766it will be checked if that change was also changed. The mechanism to assume a
767class implements an interface just because the methods happen to match is
768brittle and leads to obscure problems, let's not do that.
769
770
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000771Using "this.member" everywhere ~
772
773The object members in various programming languages can often be accessed in
774different ways, depending on the location. Sometimes "this." has to be
775prepended to avoid ambiguity. They are usually declared without "this.".
776That is quite inconsistent and sometimes confusing.
777
778A very common issue is that in the constructor the arguments use the same name
779as the object member. Then for these members "this." needs to be prefixed in
780the body, while for other members this is not needed and often omitted. This
781leads to a mix of members with and without "this.", which is inconsistent.
782
783For |Vim9| classes the "this." prefix is always used. Also for declaring the
784members. Simple and consistent. When looking at the code inside a class it's
785also directly clear which variable references are object members and which
786aren't.
787
788
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000789Using class members ~
790
791Using "static member" to declare a class member is very common, nothing new
792here. In |Vim9| script these can be accessed directly by their name. Very
793much like how a script-local variable can be used in a function. Since object
794members are always accessed with "this." prepended, it's also quickly clear
795what kind of member it is.
796
797TypeScript prepends the class name before the class member, also inside the
798class. This has two problems: The class name can be rather long, taking up
799quite a bit of space, and when the class is renamed all these places need to
800be changed too.
801
802
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000803Declaring object and class members ~
804
805The main choice is whether to use "var" as with variable declarations.
806TypeScript does not use it: >
807 class Point {
808 x: number;
809 y = 0;
810 }
811
812Following that Vim object members could be declared like this: >
813 class Point
814 this.x: number
815 this.y = 0
816 endclass
817
818Some users pointed out that this looks more like an assignment than a
819declaration. Adding "var" changes that: >
820 class Point
821 var this.x: number
822 var this.y = 0
823 endclass
824
825We also need to be able to declare class members using the "static" keyword.
826There we can also choose to leave out "var": >
827 class Point
828 var this.x: number
829 static count = 0
830 endclass
831
832Or do use it, before "static": >
833 class Point
834 var this.x: number
835 var static count = 0
836 endclass
837
838Or after "static": >
839 class Point
840 var this.x: number
841 static var count = 0
842 endclass
843
844This is more in line with "static def Func()".
845
846There is no clear preference whether to use "var" or not. The two main
847reasons to leave it out are:
8481. TypeScript, Java and other popular languages do not use it.
8492. Less clutter.
850
851
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000852Using "ClassName.new()" to construct an object ~
853
854Many languages use the "new" operator to create an object, which is actually
855kind of strange, since the constructor is defined as a method with arguments,
856not a command. TypeScript also has the "new" keyword, but the method is
857called "constructor()", it is hard to see the relation between the two.
858
859In |Vim9| script the constructor method is called new(), and it is invoked as
860new(), simple and straightforward. Other languages use "new ClassName()",
861while there is no ClassName() method, it's a method by another name in the
862class called ClassName. Quite confusing.
863
864
865Default read access to object members ~
866
867Some users will remark that the access rules for object members are
868asymmetric. Well, that is intentional. Changing a value is a very different
869action than reading a value. The read operation has no side effects, it can
870be done any number of times without affecting the object. Changing the value
871can have many side effects, and even have a ripple effect, affecting other
872objects.
873
874When adding object members one usually doesn't think much about this, just get
875the type right. And normally the values are set in the new() method.
876Therefore defaulting to read access only "just works" in most cases. And when
877directly writing you get an error, which makes you wonder if you actually want
878to allow that. This helps writing code with fewer mistakes.
879
880
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000881Making object members private with an underscore ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000882
883When an object member is private, it can only be read and changed inside the
884class (and in sub-classes), then it cannot be used outside of the class.
885Prepending an underscore is a simple way to make that visible. Various
886programming languages have this as a recommendation.
887
888In case you change your mind and want to make the object member accessible
889outside of the class, you will have to remove the underscore everywhere.
890Since the name only appears in the class (and sub-classes) they will be easy
891to find and change.
892
893The other way around is much harder: you can easily prepend an underscore to
894the object member inside the class to make it private, but any usage elsewhere
895you will have to track down and change. You may have to make it a "set"
896method call. This reflects the real world problem that taking away access
897requires work to be done for all places where that access exists.
898
899An alternative would have been using the "private" keyword, just like "public"
900changes the access in the other direction. Well, that's just to reduce the
901number of keywords.
902
903
904No protected object members ~
905
906Some languages provide several ways to control access to object members. The
907most known is "protected", and the meaning varies from language to language.
908Others are "shared", "private" and even "friend".
909
910These rules make life more difficult. That can be justified in projects where
911many people work on the same, complex code where it is easy to make mistakes.
912Especially when refactoring or other changes to the class model.
913
914The Vim scripts are expected to be used in a plugin, with just one person or a
915small team working on it. Complex rules then only make it more complicated,
Bram Moolenaar71badf92023-04-22 22:40:14 +0100916the extra safety provided by the rules isn't really needed. Let's just keep
917it simple and not specify access details.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000918
919
920==============================================================================
921
92210. To be done later
923
924Can a newSomething() constructor invoke another constructor? If yes, what are
925the restrictions?
926
927Thoughts:
928- Generics for a class: `class <Tkey, Tentry>`
929- Generics for a function: `def <Tkey> GetLast(key: Tkey)`
930- Mixins: not sure if that is useful, leave out for simplicity.
931
932Some things that look like good additions:
933- For testing: Mock mechanism
934
935An important class to be provided is "Promise". Since Vim is single
936threaded, connecting asynchronous operations is a natural way of allowing
937plugins to do their work without blocking the user. It's a uniform way to
938invoke callbacks and handle timeouts and errors.
939
940
941 vim:tw=78:ts=8:noet:ft=help:norl: