3

Does Kotlin have pointers? If yes,

  1. How to increment a Pointer?

  2. How to decrement a Pointer?

  3. How to do Pointer Comparisons?

Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53

3 Answers3

14

It has references, and it doesn't support pointer arithmetic (so you can't increment or decrement).

Note that the only thing that "having pointers" allows you is the ability to create a pointer and to dereference it.

The closest thing to a "pointer comparison" is referential equality, which is performed with the === operator.

cha0site
  • 10,517
  • 3
  • 33
  • 51
4

There is no pointers in Kotlin for low-level processing as C.

However, it's possible emulate pointers in high-level programming.

For low-level programming it is necessary using special system APIs to simulate arrays in memories, that exists in Windows, Linux, etc. Read about memory mapped files here and here. Java has library to read and write directly in memory.

Single types (numeric, string and boolean) are values, however, other types are references (high level pointers) in Kotlin, that one can compare, assign, etc.

If one needs increment or decrement pointers, just encapsulate the desired data package into a array

For simulate pointers to simple values it just wrap the value in a class:

data class pStr (   // Pointer to a String
  var s:String=""
)

fun main() {
 var st=pStr("banana")
 var tt=st
 tt.s = "melon"
 println(st.s) // display "melon"

 var s:String = "banana"
 var t:String = s
 t.s = "melon"
 println(s.s) // display "banana"
}
Paulo Buchsbaum
  • 2,471
  • 26
  • 29
3

I found this question while googling over some interesting code I found and thought that I would contribute my own proverbial "two cents". So Kotlin does have an operator which might be confused as a pointer, based on syntax, the spread operator. The spread operator is often used to pass an array as a vararg parameter.

For example, one might see something like the following line of code which looks suspiciously like the use of a pointer:

val process = ProcessBuilder(*args.toTypedArray()).start()

This line isn't calling the toTypedArray() method on a pointer to the args array, as you might expect if you come from a C/C++ background like me. Rather, this code is actually just calling the toTypedArray() method on the args array (as one would expect) and then passing the elements of the array as an arbitrary number of varargs arguments. Without the spread operator (i.e. *), a single argument would be passed, which would be the typed args array, itself.

That's the key difference: the spread operator enables the developer to pass the elements of the array as a list of varargs as opposed to passing a pointer to the array, itself, as a single argument.

I hope that helps.

entpnerd
  • 10,049
  • 8
  • 47
  • 68