vim9class.txt (47790B)
1 *vim9class.txt* For Vim version 9.2. Last change: 2026 May 21 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7 Vim9 classes, objects, interfaces, types and enums. *vim9-class* 8 9 1. Overview |Vim9-class-overview| 10 2. A simple class |Vim9-simple-class| 11 3. Class variables and methods |Vim9-class-member| 12 4. Using an abstract class |Vim9-abstract-class| 13 5. Using an interface |Vim9-using-interface| 14 6. More class details |Vim9-class| 15 7. Type definition |Vim9-type| 16 8. Enum |Vim9-enum| 17 18 9. Rationale 19 10. To be done later 20 21 ============================================================================== 22 23 1. Overview *Vim9-class-overview* 24 25 The fancy term is "object-oriented programming". You can find lots of study 26 material on this subject. Here we document what |Vim9| script provides, 27 assuming you know the basics already. Added are helpful hints about how to 28 use this functionality effectively. Vim9 classes and objects cannot be used 29 in legacy Vim scripts and legacy functions. 30 31 The basic item is an object: 32 - An object stores state. It contains one or more variables that can each 33 have a value. 34 - An object provides functions that use and manipulate its state. These 35 functions are invoked "on the object", which is what sets it apart from the 36 traditional separation of data and code that manipulates the data. 37 - An object has a well defined interface, with typed member variables and 38 methods. 39 - Objects are created from a class and all objects have the same interface. 40 This does not change at runtime, it is not dynamic. 41 42 An object can only be created by a class. A class provides: 43 - A new() method, the constructor, which returns an object for the class. 44 This method is invoked on the class name: MyClass.new(). 45 - State shared by all objects of the class: class variables (class members). 46 - A hierarchy of classes, with super-classes and sub-classes, inheritance. 47 48 An interface is used to specify properties of an object: 49 - An object can declare several interfaces that it implements. 50 - Different objects implementing the same interface can be used the same way. 51 52 The class hierarchy allows for single inheritance. Otherwise interfaces are 53 to be used where needed. 54 55 Class modeling ~ 56 57 You can model classes any way you like. Keep in mind what you are building, 58 don't try to model the real world. This can be confusing, especially because 59 teachers use real-world objects to explain class relations and you might think 60 your model should therefore reflect the real world. It doesn't! The model 61 should match your purpose. 62 63 Keep in mind that composition (an object contains other objects) is often 64 better than inheritance (an object extends another object). Don't waste time 65 trying to find the optimal class model. Or waste time discussing whether a 66 square is a rectangle or that a rectangle is a square. It doesn't matter. 67 68 69 ============================================================================== 70 71 2. A simple class *Vim9-simple-class* 72 73 Let's start with a simple example: a class that stores a text position (see 74 below for how to do this more efficiently): > 75 76 class TextPosition 77 var lnum: number 78 var col: number 79 80 def new(lnum: number, col: number) 81 this.lnum = lnum 82 this.col = col 83 enddef 84 85 def SetLnum(lnum: number) 86 this.lnum = lnum 87 enddef 88 89 def SetCol(col: number) 90 this.col = col 91 enddef 92 93 def SetPosition(lnum: number, col: number) 94 this.lnum = lnum 95 this.col = col 96 enddef 97 endclass 98 < *object* *Object* 99 You can create an object from this class with the new() method: > 100 101 var pos = TextPosition.new(1, 1) 102 < 103 The object variables "lnum" and "col" can be accessed directly: > 104 105 echo $'The text position is ({pos.lnum}, {pos.col})' 106 < *E1317* *E1327* *:this* 107 If you have been using other object-oriented languages you will notice that in 108 Vim, within a class definition, the declared object members are consistently 109 referred to with the "this." prefix. This is different from languages like 110 Java and TypeScript. The naming convention makes the object members easy to 111 spot. Also, when a variable does not have the "this." prefix you know it is 112 not an object variable. 113 *E1411* 114 From outside the class definition, access an object's methods and variables by 115 using the object name followed by a dot following by the member: > 116 117 pos.lnum 118 pos.SetCol(10) 119 < 120 *E1405* 121 A class name cannot be used as an expression. A class name cannot be used in 122 the left-hand-side of an assignment. 123 124 Object variable write access ~ 125 *read-only-variable* 126 Now try to change an object variable directly: > 127 128 pos.lnum = 9 129 < *E1335* 130 This will give you an error! That is because by default object variables can 131 be read but not set. That's why the TextPosition class provides a method for 132 it: > 133 134 pos.SetLnum(9) 135 136 Allowing to read but not set an object variable is the most common and safest 137 way. Most often there is no problem using a value, while setting a value may 138 have side effects that need to be taken care of. In this case, the SetLnum() 139 method could check if the line number is valid and either give an error or use 140 the closest valid value. 141 *:public* *public-variable* *E1331* 142 If you don't care about side effects and want to allow the object variable to 143 be changed at any time, you can make it public: > 144 145 public var lnum: number 146 public var col: number 147 148 Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting 149 "pos.lnum" directly above will no longer give an error. 150 *E1326* 151 If you try to set an object variable that doesn't exist you get an error: > 152 pos.other = 9 153 < E1326: Member not found on object "TextPosition": other ~ 154 155 *E1376* 156 A object variable cannot be accessed using the class name. 157 158 Protected variables ~ 159 *protected-variable* *E1332* *E1333* 160 On the other hand, if you do not want the object variables to be read directly 161 from outside the class or its sub-classes, you can make them protected. This 162 is done by prefixing an underscore to the name: > 163 164 var _lnum: number 165 var _col: number 166 167 Now you need to provide methods to get the value of the protected variables. 168 These are commonly called getters. We recommend using a name that starts with 169 "Get": > 170 171 def GetLnum(): number 172 return this._lnum 173 enddef 174 175 def GetCol(): number 176 return this._col 177 enddef 178 179 This example isn't very useful, the variables might as well have been public. 180 It does become useful if you check the value. For example, restrict the line 181 number to the total number of lines: > 182 183 def GetLnum(): number 184 if this._lnum > this._lineCount 185 return this._lineCount 186 endif 187 return this._lnum 188 enddef 189 < 190 Protected methods ~ 191 *protected-method* *E1366* 192 If you want object methods to be accessible only from other methods of the 193 same class and not used from outside the class, then you can make them 194 protected. This is done by prefixing the method name with an underscore: > 195 196 class SomeClass 197 def _Foo(): number 198 return 10 199 enddef 200 def Bar(): number 201 return this._Foo() 202 enddef 203 endclass 204 < 205 Accessing a protected method outside the class will result in an error (using 206 the above class): > 207 208 var a = SomeClass.new() 209 a._Foo() 210 < 211 Simplifying the new() method ~ 212 *new()* *constructor* 213 See also |default-constructor| and |multiple-constructors|. 214 215 Many constructors take values for the object variables. Thus you very often 216 see this pattern: > 217 218 class SomeClass 219 var lnum: number 220 var col: number 221 222 def new(lnum: number, col: number) 223 this.lnum = lnum 224 this.col = col 225 enddef 226 endclass 227 < 228 *E1390* 229 Not only is this text you need to write, it also has the type of each 230 variable twice. Since this is so common a shorter way to write new() is 231 provided: > 232 233 def new(this.lnum, this.col) 234 enddef 235 236 The semantics are easy to understand: Providing the object variable name, 237 including "this.", as the argument to new() means the value provided in the 238 new() call is assigned to that object variable. This mechanism comes from the 239 Dart language. 240 241 Putting together this way of using new() and making the variables public 242 results in a much shorter class definition than what we started with: > 243 244 class TextPosition 245 public var lnum: number 246 public var col: number 247 248 def new(this.lnum, this.col) 249 enddef 250 251 def SetPosition(lnum: number, col: number) 252 this.lnum = lnum 253 this.col = col 254 enddef 255 endclass 256 257 The sequence of constructing a new object is: 258 1. Memory is allocated and cleared. All values are zero/false/empty. 259 2. For each declared object variable that has an initializer, the expression 260 is evaluated and assigned to the variable. This happens in the sequence 261 the variables are declared in the class. 262 3. Arguments in the new() method in the "this.name" form are assigned. 263 4. The body of the new() method is executed. 264 265 If the class extends a parent class, the same thing happens. In the second 266 step the object variables of the parent class are initialized first. There is 267 no need to call "super()" or "new()" on the parent. 268 269 *E1365* 270 When defining the new() method the return type should not be specified. It 271 always returns an object of the class. 272 273 The new() method can be made a protected method by using "_new()". This can 274 be used to support the singleton design pattern. 275 276 *E1386* 277 When invoking an object method, the method name should be preceded by the 278 object variable name. An object method cannot be invoked using the class 279 name. 280 281 ============================================================================== 282 283 3. Class Variables and Methods *Vim9-class-member* 284 285 *:static* *E1329* *E1337* *E1338* *E1368* 286 Class members are declared with "static". They are used by the name without a 287 prefix in the class where they are defined: > 288 289 class OtherThing 290 var size: number 291 static var totalSize: number 292 293 def new(this.size) 294 totalSize += this.size 295 enddef 296 endclass 297 < *E1340* *E1341* 298 Since the name is used as-is, shadowing the name by a method argument name 299 or local variable name is not allowed. 300 301 *E1374* *E1375* *E1384* *E1385* 302 To access a class member outside of the class where it is defined, the class 303 name prefix must be used. A class member cannot be accessed using an object. 304 305 Just like object members the access can be made protected by using an 306 underscore as the first character in the name, and it can be made public by 307 prefixing "public": > 308 309 class OtherThing 310 static var total: number # anybody can read, only class can write 311 static var _sum: number # only class can read and write 312 public static var result: number # anybody can read and write 313 endclass 314 < 315 *class-method* 316 Class methods are also declared with "static". They can use the class 317 variables but they have no access to the object variables, they cannot use the 318 "this" keyword: 319 > 320 class OtherThing 321 var size: number 322 static var totalSize: number 323 324 # Clear the total size and return the value it had before. 325 static def ClearTotalSize(): number 326 var prev = totalSize 327 totalSize = 0 328 return prev 329 enddef 330 endclass 331 332 Inside the class, the class method can be called by name directly, outside the 333 class, the class name must be prefixed: `OtherThing.ClearTotalSize()`. Also, 334 the name prefix must be used for public class methods in the special contexts 335 of class variable initializers and of lambda expressions and nested functions: 336 > 337 class OtherThing 338 static var name: string = OtherThing.GiveName() 339 340 static def GiveName(): string 341 def DoGiveName(): string 342 return OtherThing.NameAny() 343 enddef 344 345 return DoGiveName() 346 enddef 347 348 static def NameAny(): string 349 return "any" 350 enddef 351 endclass 352 < 353 354 Just like object methods the access can be made protected by using an 355 underscore as the first character in the method name: > 356 357 class OtherThing 358 static def _Foo() 359 echo "Foo" 360 enddef 361 def Bar() 362 _Foo() 363 enddef 364 endclass 365 < 366 *E1370* 367 Note that constructors cannot be declared as "static". They are called like a 368 static but execute as an object method; they have access to "this". 369 370 To access the class methods and class variables of a super class in an 371 extended class, the class name prefix should be used just as from anywhere 372 outside of the defining class: > 373 374 vim9script 375 class Vehicle 376 static var nextID: number = 1000 377 static def GetID(): number 378 nextID += 1 379 return nextID 380 enddef 381 endclass 382 class Car extends Vehicle 383 var myID: number 384 def new() 385 this.myID = Vehicle.GetID() 386 enddef 387 endclass 388 < 389 Class variables and methods are not inherited by a child class. A child class 390 can declare a static variable or a method with the same name as the one in the 391 super class. Depending on the class where the member is used the 392 corresponding class member will be used. The type of the class member in a 393 child class can be different from that in the super class. 394 395 The double underscore (__) prefix for a class or object method name is 396 reserved for future use. 397 398 *object-final-variable* *E1409* 399 The |:final| keyword can be used to make a class or object variable a 400 constant. Examples: > 401 402 class A 403 final v1 = [1, 2] # final object variable 404 public final v2 = {x: 1} # final object variable 405 static final v3 = 'abc' # final class variable 406 public static final v4 = 0z10 # final class variable 407 endclass 408 < 409 A final variable can be changed only from a constructor function. Example: > 410 411 class A 412 final v1: list<number> 413 def new() 414 this.v1 = [1, 2] 415 enddef 416 endclass 417 var a = A.new() 418 echo a.v1 419 < 420 Note that the value of a final variable can be changed. Example: > 421 422 class A 423 public final v1 = [1, 2] 424 endclass 425 var a = A.new() 426 a.v1[0] = 6 # OK 427 a.v1->add(3) # OK 428 a.v1 = [3, 4] # Error 429 < 430 *E1408* 431 Final variables are not supported in an interface. A class or object method 432 cannot be final. 433 434 *object-const-variable* 435 The |:const| keyword can be used to make a class or object variable and the 436 value a constant. Examples: > 437 438 class A 439 const v1 = [1, 2] # const object variable 440 public const v2 = {x: 1} # const object variable 441 static const v3 = 'abc' # const class variable 442 public static const v4 = 0z10 # const class variable 443 endclass 444 < 445 A const variable can be changed only from a constructor function. Example: > 446 447 class A 448 const v1: list<number> 449 def new() 450 this.v1 = [1, 2] 451 enddef 452 endclass 453 var a = A.new() 454 echo a.v1 455 < 456 A const variable and its value cannot be changed. Example: > 457 458 class A 459 public const v1 = [1, 2] 460 endclass 461 var a = A.new() 462 a.v1[0] = 6 # Error 463 a.v1->add(3) # Error 464 a.v1 = [3, 4] # Error 465 < 466 *E1410* 467 Const variables are not supported in an interface. A class or object method 468 cannot be a const. 469 470 ============================================================================== 471 472 4. Using an abstract class *Vim9-abstract-class* 473 474 An abstract class forms the base for at least one sub-class. In the class 475 model one often finds that a few classes have the same properties that can be 476 shared, but a class with these properties does not have enough state to create 477 an object from. A sub-class must extend the abstract class and add the 478 missing state and/or methods before it can be used to create objects for. 479 480 For example, a Shape class could store a color and thickness. You cannot 481 create a Shape object, it is missing the information about what kind of shape 482 it is. The Shape class functions as the base for a Square and a Triangle 483 class, for which objects can be created. Example: > 484 485 abstract class Shape 486 var color = Color.Black 487 var thickness = 10 488 endclass 489 490 class Square extends Shape 491 var size: number 492 493 def new(this.size) 494 enddef 495 endclass 496 497 class Triangle extends Shape 498 var base: number 499 var height: number 500 501 def new(this.base, this.height) 502 enddef 503 endclass 504 < 505 An abstract class is defined the same way as a normal class, except that it 506 does not have any new() method. *E1359* 507 508 *abstract-method* *E1371* *E1372* 509 An abstract method can be defined in an abstract class by using the "abstract" 510 prefix when defining the method: > 511 512 abstract class Shape 513 abstract def Draw() 514 endclass 515 < 516 A static method in an abstract class cannot be an abstract method. 517 518 *E1404* 519 An interface method cannot be an abstract method. 520 521 *E1373* 522 A non-abstract class extending the abstract class must implement all the 523 abstract methods. The signature (arguments, argument types and return type) 524 must be exactly the same. If the return type of a method is a class, then 525 that class or one of its subclasses can be used in the extended method. 526 527 *E1431* 528 An abstract method in an abstract super class cannot be invoked. 529 530 ============================================================================== 531 532 5. Using an interface *Vim9-using-interface* 533 534 The example above with Shape, Square and Triangle can be made more useful if 535 we add a method to compute the surface of the object. For that we create the 536 interface called HasSurface, which specifies one method Surface() that returns 537 a number. This example extends the one above: > 538 539 abstract class Shape 540 var color = Color.Black 541 var thickness = 10 542 endclass 543 544 interface HasSurface 545 def Surface(): number 546 endinterface 547 548 class Square extends Shape implements HasSurface 549 var size: number 550 551 def new(this.size) 552 enddef 553 554 def Surface(): number 555 return this.size * this.size 556 enddef 557 endclass 558 559 class Triangle extends Shape implements HasSurface 560 var base: number 561 var height: number 562 563 def new(this.base, this.height) 564 enddef 565 566 def Surface(): number 567 return this.base * this.height / 2 568 enddef 569 endclass 570 < 571 *E1348* *E1349* *E1367* *E1382* *E1383* 572 If a class declares to implement an interface, all the items specified in the 573 interface must appear in the class, with the same types. 574 575 The interface name can be used as a type: > 576 577 var shapes: list<HasSurface> = [ 578 Square.new(12), 579 Triangle.new(8, 15), 580 ] 581 for shape in shapes 582 echo $'the surface is {shape.Surface()}' 583 endfor 584 < 585 *E1378* *E1379* *E1380* *E1387* 586 An interface can contain only object methods and read-only object variables. 587 An interface cannot contain read-write or protected object variables, 588 protected object methods, class variables and class methods. 589 590 An interface can extend another interface using "extends". The sub-interface 591 inherits all the instance variables and methods from the super interface. 592 593 An interface cannot be defined inside a function. *E1436* 594 595 ============================================================================== 596 597 6. More class details *Vim9-class* *Class* *class* 598 599 Defining a class ~ 600 *:class* *:endclass* *:abstract* 601 A class is defined between `:class` and `:endclass`. The whole class is 602 defined in one script file. It is not possible to add to a class later. 603 604 A class can only be defined in a |Vim9| script file. *E1316* 605 A class cannot be defined inside a function. *E1429* 606 607 It is possible to define more than one class in a script file. Although it 608 usually is better to export only one main class. It can be useful to define 609 types, enums and helper classes though. 610 611 The `:abstract` keyword may be prefixed and `:export` may be used. That gives 612 these variants: > 613 614 class ClassName 615 endclass 616 617 export class ClassName 618 endclass 619 620 abstract class ClassName 621 endclass 622 623 export abstract class ClassName 624 endclass 625 < 626 *E1314* 627 The class name should be CamelCased. It must start with an uppercase letter. 628 That avoids clashing with builtin types. 629 *E1315* 630 After the class name these optional items can be used. Each can appear only 631 once. They can appear in any order, although this order is recommended: > 632 extends ClassName 633 implements InterfaceName, OtherInterface 634 specifies SomeInterface 635 < 636 The "specifies" feature is currently not implemented. 637 638 *E1355* *E1369* *E1406* 639 Each variable and method name can be used only once. It is not possible to 640 define a method with the same name and different type of arguments. It is not 641 possible to use a public and protected member variable with the same name. An 642 object variable name used in a super class cannot be reused in a child class. 643 644 Object Variable Initialization ~ 645 646 *E1430* 647 If the type of a variable is not explicitly specified in a class, then it is 648 set to "any" during class definition. When an object is instantiated from the 649 class, then the type of the variable is set. 650 651 The following reserved keyword names cannot be used as an object or class 652 variable name: "super", "this", "true", "false", "null", "null_blob", 653 "null_channel", "null_class", "null_dict", "null_function", "null_job", 654 "null_list", "null_object", "null_partial" and "null_string". 655 656 Extending a class ~ 657 *extends* 658 A class can extend one other class. *E1352* *E1353* *E1354* 659 The basic idea is to build on top of an existing class, add properties to it. 660 661 The extended class is called the "base class" or "super class". The new class 662 is called the "child class". 663 664 Object variables from the base class are all taken over by the child class. 665 It is not possible to override them (unlike some other languages). 666 667 *E1356* *E1357* *E1358* 668 Object methods of the base class can be overruled. The signature (arguments, 669 argument types and return type) must be exactly the same. If the return type 670 of a method is a class, then that class or one of its subclasses can be used 671 in the extended method. The method of the base class can be called by 672 prefixing "super.". 673 674 *E1377* 675 The access level of a method (public or protected) in a child class should be 676 the same as the super class. 677 678 Other object methods of the base class are taken over by the child class. 679 680 Class methods, including methods starting with "new", can be overruled, like 681 with object methods. The method on the base class can be called by prefixing 682 the name of the class (for class methods) or "super.". 683 684 Unlike other languages, the constructor of the base class does not need to be 685 invoked. In fact, it cannot be invoked. If some initialization from the base 686 class also needs to be done in a child class, put it in an object method and 687 call that method from every constructor(). 688 689 If the base class did not specify a new() method then one was automatically 690 created. This method will not be taken over by the child class. The child 691 class can define its own new() method, or, if there isn't one, a new() method 692 will be added automatically. 693 694 695 A class implementing an interface ~ 696 *implements* *E1346* *E1347* *E1389* 697 A class can implement one or more interfaces. The "implements" keyword can 698 only appear once *E1350* . Multiple interfaces can be specified, separated by 699 commas. Each interface name can appear only once. *E1351* 700 701 A class defining an interface ~ 702 *specifies* 703 A class can declare its interface, the object variables and methods, with a 704 named interface. This avoids the need for separately specifying the 705 interface, which is often done in many languages, especially Java. 706 TODO: This is currently not implemented. 707 708 Items in a class ~ 709 *E1318* *E1325* *E1388* 710 Inside a class, in between `:class` and `:endclass`, these items can appear: 711 - An object variable declaration: > 712 var _protectedVariableName: memberType 713 var readonlyVariableName: memberType 714 public var readwriteVariableName: memberType 715 - A class variable declaration: > 716 static var _protectedClassVariableName: memberType 717 static var readonlyClassVariableName: memberType 718 public static var readwriteClassVariableName: memberType 719 - A constructor method: > 720 def new(arguments) 721 def newName(arguments) 722 - A class method: > 723 static def SomeMethod(arguments) 724 static def _ProtectedMethod(arguments) 725 - An object method: > 726 def SomeMethod(arguments) 727 def _ProtectedMethod(arguments) 728 729 For the object variable the type must be specified. The best way is to do 730 this explicitly with ": {type}". For simple types you can also use an 731 initializer, such as "= 123", and Vim will see that the type is a number. 732 Avoid doing this for more complex types and when the type will be incomplete. 733 For example: > 734 var nameList = [] 735 This specifies a list, but the item type is unknown. Better use: > 736 var nameList: list<string> 737 The initialization isn't needed, the list is empty by default. 738 *E1330* 739 Some types cannot be used, such as "void", "null" and "v:none". 740 741 Builtin Object Methods ~ 742 *builtin-object-methods* 743 Some of the builtin functions like |empty()|, |len()| and |string()| can be 744 used with an object. An object can implement a method with the same name as 745 these builtin functions to return an object-specific value. 746 747 *E1412* 748 The following builtin methods are supported: 749 *object-empty()* 750 empty() Invoked by the |empty()| function to check whether an object is 751 empty. If this method is missing, then true is returned. This 752 method should not accept any arguments and must return a boolean. 753 *object-len()* 754 len() Invoked by the |len()| function to return the length of an 755 object. If this method is missing in the class, then an error is 756 given and zero is returned. This method should not accept any 757 arguments and must return a number. 758 *object-string()* 759 string() Invoked by the |string()| function to get a textual 760 representation of an object. Also used by the |:echo| command 761 for an object. If this method is missing in the class, then a 762 built-in default textual representation is used. This method 763 should not accept any arguments and must return a string. 764 765 *E1413* 766 A class method cannot be used as a builtin method. 767 768 Defining an interface ~ 769 *interface* *Interface* *:interface* *:endinterface* 770 An interface is defined between `:interface` and `:endinterface`. It may be 771 prefixed with `:export`: > 772 773 interface InterfaceName 774 endinterface 775 776 export interface InterfaceName 777 endinterface 778 < *E1344* 779 An interface can declare object variables, just like in a class but without 780 any initializer. 781 *E1345* 782 An interface can declare methods with `:def`, including the arguments and 783 return type, but without the body and without `:enddef`. Example: > 784 785 interface HasSurface 786 var size: number 787 def Surface(): number 788 endinterface 789 790 An interface name must start with an uppercase letter. *E1343* 791 The "Has" prefix can be used to make it easier to guess this is an interface 792 name, with a hint about what it provides. 793 An interface can only be defined in a |Vim9| script file. *E1342* 794 An interface cannot "implement" another interface but it can "extend" another 795 interface. *E1381* 796 797 null object ~ 798 799 When a variable is declared to have the type of an object, but it is not 800 initialized, the value is null. When trying to use this null object Vim often 801 does not know what class was supposed to be used. Vim then cannot check if 802 a variable name is correct and you will get a "Using a null object" error, 803 even when the variable name is invalid. *E1360* *E1362* 804 805 Default constructor ~ 806 *default-constructor* 807 In case you define a class without a new() method, one will be automatically 808 defined. This default constructor will have arguments for all the object 809 variables, in the order they were specified. Thus if your class looks like: > 810 811 class AutoNew 812 var name: string 813 var age: number 814 var gender: Gender 815 endclass 816 817 Then the default constructor will be: > 818 819 def new(this.name = v:none, this.age = v:none, this.gender = v:none) 820 enddef 821 822 The "= v:none" default values make the arguments optional. Thus you can also 823 call `new()` without any arguments. No assignment will happen and the default 824 value for the object variables will be used. This is a more useful example, 825 with default values: > 826 827 class TextPosition 828 var lnum: number = 1 829 var col: number = 1 830 endclass 831 832 If you want the constructor to have mandatory arguments, you need to write it 833 yourself. For example, if for the AutoNew class above you insist on getting 834 the name, you can define the constructor like this: > 835 836 def new(this.name, this.age = v:none, this.gender = v:none) 837 enddef 838 < 839 When using the default new() method, if the order of the object variables in 840 the class is changed later, then all the callers of the default new() method 841 need to change. To avoid this, the new() method can be explicitly defined 842 without any arguments. 843 844 *E1328* 845 Note that you cannot use another default value than "v:none" here. If you 846 want to initialize the object variables, do it where they are declared. This 847 way you only need to look in one place for the default values. 848 849 All object variables will be used in the default constructor, including 850 protected access ones. 851 852 If the class extends another one, the object variables of that class will come 853 first. 854 855 856 Multiple constructors ~ 857 *multiple-constructors* 858 Normally a class has just one new() constructor. In case you find that the 859 constructor is often called with the same arguments you may want to simplify 860 your code by putting those arguments into a second constructor method. For 861 example, if you tend to use the color black a lot: > 862 863 def new(this.garment, this.color, this.size) 864 enddef 865 ... 866 var pants = new(Garment.pants, Color.black, "XL") 867 var shirt = new(Garment.shirt, Color.black, "XL") 868 var shoes = new(Garment.shoes, Color.black, "45") 869 870 Instead of repeating the color every time you can add a constructor that 871 includes it: > 872 873 def newBlack(this.garment, this.size) 874 this.color = Color.black 875 enddef 876 ... 877 var pants = newBlack(Garment.pants, "XL") 878 var shirt = newBlack(Garment.shirt, "XL") 879 var shoes = newBlack(Garment.shoes, "9.5") 880 881 Note that the method name must start with "new". If there is no method called 882 "new()" then the default constructor is added, even though there are other 883 constructor methods. 884 885 Using variable type "any" for an Object~ 886 *obj-var-type-any* 887 You can use a variable declared with type "any" to hold an object. e.g. 888 > 889 vim9script 890 class A 891 var n = 10 892 def Get(): number 893 return this.n 894 enddef 895 endclass 896 897 def Fn(o: any) 898 echo o.n 899 echo o.Get() 900 enddef 901 902 var a = A.new() 903 Fn(a) 904 < 905 In this example, Vim cannot determine the type of the parameter "o" for 906 function Fn() at compile time. It can be either a |Dict| or an |Object| 907 value. Therefore, at runtime, when the type is known, the object member 908 variable and method are looked up. This process is not efficient, so it is 909 recommended to use a more specific type whenever possible for better 910 efficiency. 911 912 Compiling methods in a Class ~ 913 *class-compile* 914 The |:defcompile| command can be used to compile all the class and object 915 methods defined in a class: > 916 917 defcompile MyClass # Compile class "MyClass" 918 defcompile # Compile the classes in the current script 919 < 920 ============================================================================== 921 922 7. Type definition *typealias* *Vim9-type* *:type* 923 924 *E1393* *E1396* *E1397* *E1398* 925 A type definition is giving a name to a type specification. This is also 926 known as a "type alias". The type alias can be used wherever a built-in type 927 can be used. Example: > 928 929 type ListOfStrings = list<string> 930 var s: ListOfStrings = ['a', 'b'] 931 932 def ProcessStr(str: ListOfStrings): ListOfStrings 933 return str 934 enddef 935 echo ProcessStr(s) 936 < 937 *E1394* 938 A type alias name must start with an upper case character. Only existing 939 types can be aliased. 940 941 *E1399* 942 A type alias can be created only at the script level and not inside a 943 function. A type alias can be exported and used across scripts. 944 945 *E1403* *E1407* 946 A type alias cannot be used as an expression. A type alias cannot be used in 947 the left-hand-side of an assignment. 948 949 For a type alias name, the |typename()| function returns the type that is 950 aliased: > 951 952 type ListOfStudents = list<dict<any>> 953 echo typename(ListOfStudents) 954 typealias<list<dict<any>>> 955 < 956 ============================================================================== 957 958 8. Enum *Vim9-enum* *:enum* *:endenum* 959 960 *enum* *E1418* *E1419* *E1420* 961 An enum is a type that can have one of a list of values. Example: > 962 963 enum Color 964 White, 965 Red, 966 Green, Blue, Black 967 endenum 968 < 969 *enumvalue* *E1422* *E1428* 970 The enum values are separated by commas. More than one enum value can be 971 listed in a single line. The final enum value should not be followed by a 972 comma. Duplicate enum values are not allowed. 973 974 An enum value is accessed using the enum name followed by the value name: > 975 976 var a: Color = Color.Blue 977 < 978 Enums are treated as classes, where each enum value is essentially an instance 979 of that class. Unlike typical object instantiation with the |new()| method, 980 enum instances cannot be created this way. 981 982 An enum can only be defined in a |Vim9| script file. *E1414* 983 An enum cannot be defined inside a function. *E1435* 984 985 *E1415* 986 An enum name must start with an uppercase letter. The name of an enum value 987 in an enum can start with an upper or lowercase letter. 988 989 *E1416* 990 An enum can implement an interface but cannot extend a class: > 991 992 enum MyEnum implements MyIntf 993 Value1, 994 Value2 995 996 def SomeMethod() 997 enddef 998 endenum 999 < 1000 *enum-constructor* 1001 The enum value objects in an enum are constructed like any other objects using 1002 the |new()| method. Arguments can be passed to the enum constructor by 1003 specifying them after the enum value name, just like calling a function. The 1004 default constructor doesn't have any arguments. 1005 1006 *E1417* 1007 An enum can contain class variables, class methods, object variables and 1008 object methods. The methods in an enum cannot be |:abstract| methods. 1009 1010 The following example shows an enum with object variables and methods: > 1011 1012 vim9script 1013 enum Planet 1014 Earth(1, false), 1015 Jupiter(95, true), 1016 Saturn(146, true) 1017 1018 var moons: number 1019 var has_rings: bool 1020 def GetMoons(): number 1021 return this.moons 1022 enddef 1023 endenum 1024 echo Planet.Jupiter.GetMoons() 1025 echo Planet.Earth.has_rings 1026 < 1027 *E1421* *E1423* *E1424* *E1425* 1028 Enums and their values are immutable. They cannot be utilized as numerical or 1029 string types. Enum values can declare mutable instance variables. 1030 1031 *enum-name* *E1427* 1032 Each enum value object has a "name" instance variable which contains the name 1033 of the enum value. This is a readonly variable. 1034 1035 *enum-ordinal* *E1426* 1036 Each enum value has an associated ordinal number starting with 0. The ordinal 1037 number of an enum value can be accessed using the "ordinal" instance variable. 1038 This is a readonly variable. Note that if the ordering of the enum values in 1039 an enum is changed, then their ordinal values will also change. 1040 1041 *enum-values* 1042 All the values in an enum can be accessed using the "values" class variable 1043 which is a List of the enum objects. This is a readonly variable. 1044 1045 Example: > 1046 enum Planet 1047 Mercury, 1048 Venus, 1049 Earth 1050 endenum 1051 1052 echo Planet.Mercury 1053 echo Planet.Venus.name 1054 echo Planet.Venus.ordinal 1055 for p in Planet.values 1056 # ... 1057 endfor 1058 < 1059 An enum is a class with class variables for the enum value objects and object 1060 variables for the enum value name and the enum value ordinal: > 1061 1062 enum Planet 1063 Mercury, 1064 Venus 1065 endenum 1066 < 1067 The above enum definition is equivalent to the following class definition: > 1068 1069 class Planet 1070 public static final Mercury: Planet = Planet.new('Mercury', 0) 1071 public static final Venus: Planet = Planet.new('Venus', 1) 1072 1073 public static const values: list<Planet> = [Planet.Mercury, Planet.Venus] 1074 1075 public const name: string 1076 public const ordinal: number 1077 endclass 1078 < 1079 A enum can contain object variables and methods just like a regular class: > 1080 1081 enum Color 1082 Cyan([0, 255, 255]), 1083 Magenta([255, 0, 255]), 1084 Gray([128, 128, 128]) 1085 1086 var rgb_values: list<number> 1087 1088 def Get_RGB(): list<number> 1089 return this.rgb_values 1090 enddef 1091 endenum 1092 echo Color.Magenta.Get_RGB() 1093 < 1094 ============================================================================== 1095 1096 9. Rationale 1097 1098 Most of the choices for |Vim9| classes come from popular and recently 1099 developed languages, such as Java, TypeScript and Dart. The syntax has been 1100 made to fit with the way Vim script works, such as using `endclass` instead of 1101 using curly braces around the whole class. 1102 1103 Some common constructs of object-oriented languages were chosen very long ago 1104 when this kind of programming was still new, and later found to be 1105 sub-optimal. By this time those constructs were widely used and changing them 1106 was not an option. In Vim we do have the freedom to make different choices, 1107 since classes are completely new. We can make the syntax simpler and more 1108 consistent than what "old" languages use. Without diverting too much, it 1109 should still mostly look like what you know from existing languages. 1110 1111 Some recently developed languages add all kinds of fancy features that we 1112 don't need for Vim. But some have nice ideas that we do want to use. 1113 Thus we end up with a base of what is common in popular languages, dropping 1114 what looks like a bad idea, and adding some nice features that are easy to 1115 understand. 1116 1117 The main rules we use to make decisions: 1118 - Keep it simple. 1119 - No surprises, mostly do what other languages are doing. 1120 - Avoid mistakes from the past. 1121 - Avoid the need for the script writer to consult the help to understand how 1122 things work, most things should be obvious. 1123 - Keep it consistent. 1124 - Aim at an average size plugin, not at a huge project. 1125 1126 1127 Using new() for the constructor ~ 1128 1129 Many languages use the class name for the constructor method. A disadvantage 1130 is that quite often this is a long name. And when changing the class name all 1131 constructor methods need to be renamed. Not a big deal, but still a 1132 disadvantage. 1133 1134 Other languages, such as TypeScript, use a specific name, such as 1135 "constructor()". That seems better. However, using "new" or "new()" to 1136 create a new object has no obvious relation with "constructor()". 1137 1138 For |Vim9| script using the same method name for all constructors seemed like 1139 the right choice, and by calling it new() the relation between the caller and 1140 the method being called is obvious. 1141 1142 No overloading of the constructor ~ 1143 1144 In Vim script, both legacy and |Vim9| script, there is no overloading of 1145 methods. That means it is not possible to use the same method name with 1146 different types of arguments. Therefore there also is only one new() 1147 constructor. 1148 1149 With |Vim9| script it would be possible to support overloading, since 1150 arguments are typed. However, this gets complicated very quickly. Looking at 1151 a new() call one has to inspect the types of the arguments to know which of 1152 several new() methods is actually being called. And that can require 1153 inspecting quite a bit of code. For example, if one of the arguments is the 1154 return value of a method, you need to find that method to see what type it is 1155 returning. 1156 1157 Instead, every constructor has to have a different name, starting with "new". 1158 That way multiple constructors with different arguments are possible, while it 1159 is very easy to see which constructor is being used. And the type of 1160 arguments can be properly checked. 1161 1162 No overloading of methods ~ 1163 1164 Same reasoning as for the constructor: It is often not obvious what type 1165 arguments have, which would make it difficult to figure out what method is 1166 actually being called. Better just give the methods a different name, then 1167 type checking will make sure it works as you intended. This rules out 1168 polymorphism, which we don't really need anyway. 1169 1170 Single inheritance and interfaces ~ 1171 1172 Some languages support multiple inheritance. Although that can be useful in 1173 some cases, it makes the rules of how a class works quite complicated. 1174 Instead, using interfaces to declare what is supported is much simpler. The 1175 very popular Java language does it this way, and it should be good enough for 1176 Vim. The "keep it simple" rule applies here. 1177 1178 Explicitly declaring that a class supports an interface makes it easy to see 1179 what a class is intended for. It also makes it possible to do proper type 1180 checking. When an interface is changed any class that declares to implement 1181 it will be checked if that change was also changed. The mechanism to assume a 1182 class implements an interface just because the methods happen to match is 1183 brittle and leads to obscure problems, let's not do that. 1184 1185 Using "this.variable" everywhere ~ 1186 1187 The object variables in various programming languages can often be accessed in 1188 different ways, depending on the location. Sometimes "this." has to be 1189 prepended to avoid ambiguity. They are usually declared without "this.". 1190 That is quite inconsistent and sometimes confusing. 1191 1192 A very common issue is that in the constructor the arguments use the same name 1193 as the object variable. Then for these variables "this." needs to be prefixed 1194 in the body, while for other variables this is not needed and often omitted. 1195 This leads to a mix of variables with and without "this.", which is 1196 inconsistent. 1197 1198 For |Vim9| classes the "this." prefix is always used for declared methods and 1199 variables. Simple and consistent. When looking at the code inside a class 1200 it's also directly clear which variable references are object variables and 1201 which aren't. 1202 1203 Using class variables ~ 1204 1205 Using "static variable" to declare a class variable is very common, nothing 1206 new here. In |Vim9| script these can be accessed directly by their name. 1207 Very much like how a script-local variable can be used in a method. Since 1208 object variables are always accessed with "this." prepended, it's also quickly 1209 clear what kind of variable it is. 1210 1211 TypeScript prepends the class name before the class variable name, also inside 1212 the class. This has two problems: The class name can be rather long, taking 1213 up quite a bit of space, and when the class is renamed all these places need 1214 to be changed too. 1215 1216 Declaring object and class variables ~ 1217 1218 The main choice is whether to use "var" as with variable declarations. 1219 TypeScript does not use it: > 1220 class Point { 1221 x: number; 1222 y = 0; 1223 } 1224 1225 Following that Vim object variables could be declared like this: > 1226 class Point 1227 this.x: number 1228 this.y = 0 1229 endclass 1230 1231 Some users pointed out that this looks more like an assignment than a 1232 declaration. Adding "var" and omitting "this." changes that: > 1233 class Point 1234 var x: number 1235 var y = 0 1236 endclass 1237 1238 We also need to be able to declare class variables using the "static" keyword. 1239 There we can also choose to leave out "var": > 1240 class Point 1241 var x: number 1242 static count = 0 1243 endclass 1244 1245 Or do use it, before "static": > 1246 class Point 1247 var x: number 1248 var static count = 0 1249 endclass 1250 1251 Or after "static": > 1252 class Point 1253 var x: number 1254 static var count = 0 1255 endclass 1256 1257 This is more in line with "static def Func()". 1258 1259 There is no clear preference whether to use "var" or not. The two main 1260 reasons to leave it out are: 1261 1. TypeScript and other popular languages do not use it. 1262 2. Less clutter. 1263 1264 However, it is more common for languages to reuse their general variable and 1265 function declaration syntax for class/object variables and methods. Vim9 also 1266 reuses the general function declaration syntax for methods. So, for the sake 1267 of consistency, we require "var" in these declarations. 1268 1269 Using "ClassName.new()" to construct an object ~ 1270 1271 Many languages use the "new" operator to create an object, which is actually 1272 kind of strange, since the constructor is defined as a method with arguments, 1273 not a command. TypeScript also has the "new" keyword, but the method is 1274 called "constructor()", it is hard to see the relation between the two. 1275 1276 In |Vim9| script the constructor method is called new(), and it is invoked as 1277 new(), simple and straightforward. Other languages use "new ClassName()", 1278 while there is no ClassName() method, it's a method by another name in the 1279 class called ClassName. Quite confusing. 1280 1281 1282 Vim9class access modes ~ 1283 *vim9-access-modes* 1284 The variable access modes, and their meaning, supported by Vim9class are 1285 |public-variable| read and write from anywhere 1286 |read-only-variable| read from anywhere, write from inside the 1287 class and sub-classes 1288 |protected-variable| read and write from inside the class and 1289 sub-classes 1290 1291 The method access modes are similar, but without the read-only mode. 1292 1293 1294 Default read access to object variables ~ 1295 1296 Some users will remark that the access rules for object variables are 1297 asymmetric. Well, that is intentional. Changing a value is a very different 1298 action than reading a value. The read operation has no side effects, it can 1299 be done any number of times without affecting the object. Changing the value 1300 can have many side effects, and even have a ripple effect, affecting other 1301 objects. 1302 1303 When adding object variables one usually doesn't think much about this, just 1304 get the type right. And normally the values are set in the new() method. 1305 Therefore defaulting to read access only "just works" in most cases. And when 1306 directly writing you get an error, which makes you wonder if you actually want 1307 to allow that. This helps writing code with fewer mistakes. 1308 1309 1310 Making object variables protected with an underscore ~ 1311 1312 When an object variable is protected, it can only be read and changed inside 1313 the class (and in sub-classes), then it cannot be used outside of the class. 1314 Prepending an underscore is a simple way to make that visible. Various 1315 programming languages have this as a recommendation. 1316 1317 In case you change your mind and want to make the object variable accessible 1318 outside of the class, you will have to remove the underscore everywhere. 1319 Since the name only appears in the class (and sub-classes) they will be easy 1320 to find and change. 1321 1322 The other way around is much harder: you can easily prepend an underscore to 1323 the object variable inside the class to make it protected, but any usage 1324 elsewhere you will have to track down and change. You may have to make it a 1325 "set" method call. This reflects the real world problem that taking away 1326 access requires work to be done for all places where that access exists. 1327 1328 An alternative would have been using the "protected" keyword, just like 1329 "public" changes the access in the other direction. Well, that's just to 1330 reduce the number of keywords. 1331 1332 No private object variables ~ 1333 1334 Some languages provide several ways to control access to object variables. 1335 The most known is "protected", and the meaning varies from language to 1336 language. Others are "shared", "private", "package" and even "friend". 1337 1338 These rules make life more difficult. That can be justified in projects where 1339 many people work on the same, complex code where it is easy to make mistakes. 1340 Especially when refactoring or other changes to the class model. 1341 1342 The Vim scripts are expected to be used in a plugin, with just one person or a 1343 small team working on it. Complex rules then only make it more complicated, 1344 the extra safety provided by the rules isn't really needed. Let's just keep 1345 it simple and not specify access details. 1346 1347 1348 ============================================================================== 1349 1350 10. To be done later 1351 1352 Can a newSomething() constructor invoke another constructor? If yes, what are 1353 the restrictions? 1354 1355 Thoughts: 1356 - Generics for a class: `class <Tkey, Tentry>` 1357 - Mixins: not sure if that is useful, leave out for simplicity. 1358 1359 Some things that look like good additions: 1360 - For testing: Mock mechanism 1361 1362 An important class to be provided is "Promise". Since Vim is single 1363 threaded, connecting asynchronous operations is a natural way of allowing 1364 plugins to do their work without blocking the user. It's a uniform way to 1365 invoke callbacks and handle timeouts and errors. 1366 1367 1368 vim:tw=78:ts=8:noet:ft=help:norl: