vim9 instanceof

27 views
Skip to first unread message

Ernie Rael

unread,
Feb 10, 2023, 2:57:38 PM2/10/23
to vim...@googlegroups.com

For now I'm using

export def IsInstanceOf(o: any, type: string): bool
    return type(o) == v:t_object && type == typename(o)[7 : -2]
enddef

Is there something better? A planned builtin?

I don't actually need it yet, but I'm just getting started and I know how I am.

-ernie

Bram Moolenaar

unread,
Feb 10, 2023, 3:50:26 PM2/10/23
to vim...@googlegroups.com, Ernie Rael
Implementing "instanceof" is in the todo list. I haven't looked into
the details yet. Probably similar to how Java works. Although I have
always found it a bit confusing that it results in true for an object
that is a child of the class being tested with.

I have also been thinking of an alternative of type() that includes the
exact class. So that you could do:

type_ext(object) == type_ext(SomeClass.new())

Similar to typename(), except that it would make a difference between
classes with the same name declared in different scripts. Hmm, perhaps
adding the script number would work? Thus if you define a class MyClass
in script 4 and script 7, you would get:
object<MyClass/4>
object<MyClass/7>

This win't work if a class can be defined more than once in one script
file. E.g. when it's local to a function. An alternative is to give
each encountered class a unique number.

--
hundred-and-one symptoms of being an internet addict:
112. You are amazed that anyone uses a phone without data...let
alone hear actual voices.

/// Bram Moolenaar -- Br...@Moolenaar.net -- http://www.Moolenaar.net \\\
/// \\\
\\\ sponsor Vim, vote for features -- http://www.Vim.org/sponsor/ ///
\\\ help me help AIDS victims -- http://ICCF-Holland.org ///

Ernie Rael

unread,
Feb 12, 2023, 1:25:06 PM2/12/23
to vim...@googlegroups.com
On 23/02/10 12:50 PM, Bram Moolenaar wrote:

      
For now I'm using

    export def IsInstanceOf(o: any, type: string): bool
         return type(o) == v:t_object && type == typename(o)[7 : -2]
    enddef

Is there something better? A planned builtin?

I don't actually need it yet, but I'm just getting started and I know 
how I am.
Implementing "instanceof" is in the todo list.  I haven't looked into
the details yet.  Probably similar to how Java works.  Although I have
always found it a bit confusing that it results in true for an object
that is a child of the class being tested with.

Yeah, In Java's java.lang.Class, there's both "isInstance(Object)" and
"isAssignableFrom(Class<?>); they both basically test assignment compatibility,
same as the languages "instanceof" operator.

And with that reminder, I'm changing the name of my temporary helper class to

export def IsSameType(o: any, type: string): bool

since it doesn't test assignment compatibility. (And for now don't worry about
same class name but different file.)

-ernie

Reply all
Reply to author
Forward
0 new messages