简体   繁体   中英

Groovy: Access class.value without calling getValue()

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM