用Java模拟指针?在科特林?

Bas*_*que 5 java types pointers

我试图模拟在另一个模糊的编程范例中使用的一种指针,所以我可以将一些代码移植到Java.另一种语言不是面向对象的,而是 Pascal的松散灵感.

在原始语言中,我们可以编写这样的代码.首先,使用文本.

// Start with text.
Text myVar = "Bonjour" 
Pointer myPointer = ->myVar       // Referencing a string variable, storing the reference in another variable of type `Pointer`.
Message( myPointer-> )    // Dereferencing the pointer, to retrieve `myVar`, and pass the string to a command `Display` that displays the message on screen in a dialog box.
Run Code Online (Sandbox Code Playgroud)

然后,切换到数字.

// Switch gears, to work with an number.
Integer vResult = ( Random % ( vEnd - vStart + 1 ) ) + vStart  // Generate random number.
myPointer = ->vResult    // The same pointer now points to numeric variable rather than a textual variable. 
Run Code Online (Sandbox Code Playgroud)

我们可以通过变量名的文本分配指针.

myPointer = Get pointer( "var" + String($i) ) // Generate pointer variable named `var1`, or `var2`, etc.
Run Code Online (Sandbox Code Playgroud)

我们可以向指针询问代码号,该代码号表示它所指向的值的数据类型(指示对象的数据类型).

typeCodeNumber = Type( myPointer ) // Returns 11 for an integer, 22 for text.
Run Code Online (Sandbox Code Playgroud)

在另一种语言中,编译器确实提供了类型安全性.但是当以这种方式使用指针时,我们牺牲了类型安全性.编译器会发出一个警告,指出代码使用方式与类型有关.

我对端口知道这个代码是定义XPointer为类型类以及类,如XTextXInteger.

我需要持有对十几种特定已知类型的对象的引用,包括另一个指针.我可以硬编码十几种类型,不需要对所有类型开放.

这十几种类型不共享接口,也不共享抽象类Object.即使他们共享一个接口/超类,我也不希望它们作为超类返回,而是作为原始的具体类返回.当他们进入指针时,它们应该从指针中出现.

我目前的计划是定义一个XPointer在Java类与一对引用间接引用的方法:

  • XPointer::ref( x )在那里你传递的对象Dog,Truck或者Sculpture类,甚至是另一个XPointer对象.
  • XPointer::deref ? x其中x是被识别为其原始类型的对象,a Dog,a Truck,Sculpture或甚至是另一个XPointer对象,而不仅仅是一个Object对象.

➥有没有办法做这个Java?也许与泛型

➥如果在Java中不可能,我可能不情愿地切换到Kotlin.可以在JVM上运行的Kotlin中完成此指针功能吗?

所以编码我看起来像这样:

XPointer p = new XPointer() ;  // Points to nothing, null.

p.ref( new Dog() ) ;           // Pointer points to a `Dog` object.
p.deref().bark() ;             // Pointer can retrieve the `Dog` as such, a `Dog` object.

p.ref( someTruck ) ;           // The pointer can switch to pointing to an object of an entirely different type. The `Dog` object has been replaced by a `Truck` object.
p.deref().honk() ;             // Dereference the stored `Truck` object as such.
Run Code Online (Sandbox Code Playgroud)

并指向指针.

XPointer p2 = new XPointer() ; // Points to nothing, null.
p2.ref( p ) ;                  // 2nd pointer points to a pointer that points to a `Truck` object.
p2.deref().deref().honk() ;    // Dereference the stored `Truck` object as such.
Run Code Online (Sandbox Code Playgroud)

如果有更好的路径进行这样的指针模拟,我愿意接受建议.优雅不是必需的; 任何黑客都会这样做.

Sla*_*mir 2

这称为联合变体类型(请参阅C++ 中的Boost.Variant)。后者特别方便,因为它是一组异构类型的类型安全容器,并且最接近您对要从中移植的代码类型的描述。由于 Java 不支持模板 -不,泛型不是模板- 您将无法得到您正在寻找的确切内容。

可选类型是两种类型中最简单的情况:类型 T 和 Null。鉴于您要求存储超过类型 T 或 Null,它对您不起作用。

您可能想查看JavaSealedUnions。此外,Kotlin 提供了密封类的概念,有助于将值限制为约束集中的一种类型。

祝你好运!