Sunday, January 15, 2023

[Vim 9 script] Is there a way to get the actual type of an object?

Silly example:

vim9script

class Num
this.n = 0
endclass

class Even extends Num
def new(this.n)
if this.n % 2 == 1
throw 'Not even'
endif
enddef

def IsPrime(): bool
return this.n == 2
enddef
endclass

class Odd extends Num
def new(this.n)
if this.n % 2 == 0
throw 'Not odd'
endif
enddef

def IsDivisibleByFive(): bool
return this.n % 5 == 0
enddef
endclass

def Random(): Num
const n = rand() % 16
return n % 2 == 0 ? Even.new(n) : Odd.new(n)
enddef

const v = Random()
if # v is instance of Odd()
echo v.IsDivisibleByFive()
else
echo v.IsPrime()
endif

Is there a way to distinguish the class of the value returned by
Random()?

Thanks,
Life.

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/tq1hm3%24ue2%241%40ciao.gmane.io.

No comments: