patch 9.1.1105: Vim9: no support for protected new() method
Problem: Vim9: no support for protected new() method
Solution: support the protected "_new()" object method
(Yegappan Lakshmanan)
closes: #16604
Signed-off-by: Yegappan Lakshmanan <yegappan@yahoo.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/testdir/test_vim9_class.vim b/src/testdir/test_vim9_class.vim
index 0b3ea4a..7a269fc 100644
--- a/src/testdir/test_vim9_class.vim
+++ b/src/testdir/test_vim9_class.vim
@@ -12374,4 +12374,39 @@
v9.CheckSourceSuccess(lines)
enddef
+" Test for using a protected new() method (singleton design pattern)
+def Test_protected_new_method()
+ var lines =<< trim END
+ vim9script
+ class A
+ def _new()
+ enddef
+ endclass
+ var a = A.new()
+ END
+ v9.CheckSourceFailure(lines, 'E1325: Method "new" not found in class "A"', 6)
+
+ lines =<< trim END
+ vim9script
+ class A
+ static var _instance: A
+ var str: string
+ def _new(str: string)
+ this.str = str
+ enddef
+ static def GetInstance(str: string): A
+ if _instance == null
+ _instance = A._new(str)
+ endif
+ return _instance
+ enddef
+ endclass
+ var a: A = A.GetInstance('foo')
+ var b: A = A.GetInstance('bar')
+ assert_equal('foo', a.str)
+ assert_equal('foo', b.str)
+ END
+ v9.CheckSourceSuccess(lines)
+enddef
+
" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker