0

I can't find information about this. I wrote a DataType class and want to return the value property as the default

MyInteger{
  Integer value

  MyInteger(Integer iv)
  { 
     this.value = iv
  }
}

How can I get the value without calling getValue() ?

MyInteger i = new MyInteger(5)
print i.value //works
print i.getValue() //works
print i //this is what I want to achieve
Integer realInt = i //or more specific this 

The Standard Integer is capable of that, but how? Thanks for any hint!

  • Unfortunately not... The print is just an example. Maybe it gets clearer if I would say: `Integer realInt = new MyInteger(5)` – blickfangQ2 Jun 23 '22 at 07:03
  • 1
    You can implement asType so that “Integer realInt = i” works as you’d expect. – emilles Jun 24 '22 at 01:39
  • For “print i” to work you just need to implement toString. – emilles Jun 24 '22 at 01:40
  • Sorry, I was mistaken about asType. It is used for “i as Integer”. But the Number conversion (discussed below) is built into DefaultTypeTransformation#castToType so you can do a direct assignment to an Integer variable. – emilles Jun 24 '22 at 15:28
  • Also interesting. I’ll test it too after my vacation! – blickfangQ2 Jun 24 '22 at 21:42

1 Answers1

0

Not sure what was your intent, but a "new integer" can be crafted and used like so:

@groovy.transform.TupleConstructor()
class MyInteger extends Number {

  Integer value

  @Override
  int intValue() {
    value.intValue()
  }

  @Override
  long longValue() {
    value.longValue()
  }

  @Override
  float floatValue() {
    value.floatValue()
  }

  @Override
  double doubleValue() {
    value.doubleValue()
  }
}

def my = new MyInteger(4)

assert my.value == 4
assert my.getValue() == 4

int integer = (int)my
assert integer == 4
injecteer
  • 20,038
  • 4
  • 45
  • 89