Posted January 15, 20214 yr LazyOptional<T> is used for a return value. How can I cast the output to LazyOptional? public class IHaveMana implements ICapabilitySerializable<INBT> { @CapabilityInject(IState.class) public static final Capability<IState> STATE_CAPABILITY = null; private IState instance = STATE_CAPABILITY.getDefaultInstance(); @Override public <T> LazyOptional<T> getCapability(Capability<T> capability, Direction side) { return capability == STATE_CAPABILITY ? STATE_CAPABILITY.<T>cast(this.instance) : null; //this part. } //override, override, override... }
January 15, 20214 yr I usually do it like this: return STATE_CAPABILITY.orEmpty(capability, LazyOptional.of(() -> instance)); EDIT: This is the simple but very wrong answer! As diesieben07 points out further down in the thread, you should absolutely cache the LazyOptional in a field to avoid creating a new LazyOptional every time getCapability() is called. Edited January 15, 20214 yr by vemerion
January 15, 20214 yr 2 minutes ago, diesieben07 said: Do not create a new LazyOptional every time. This defeats the entire purpose of LazyOptional. Of course you are right! However I wanted to provide a as simple solution as possible, which is why I left out that part.
January 15, 20214 yr 47 minutes ago, diesieben07 said: There is no point providing a "simple solution" which looks like "just copy this and you'll be fine" if that solution is blatantly wrong and you don't even mention what is wrong about it. You are right. I opted for the easy and wrong answer, and then tried to explain it away. I have updated my original answer, and I hope you can find it in your heart to forgive me! 47 minutes ago, e2rifia said: Is (LazyOptional)instance better? What you should do is change the type of your instance field to the type LazyOptional<IState>, which you should initialize to LazyOptional.of(() -> STATE_CAPABILITY.getDefaultInstance()), to avoid creating a new LazyOptional every time getCapability() is called. Note that you might have to slightly change some of your other methods to accommodate for the fact that instance now is a LazyOptional. Here is another thread which also discusses why you should cache the capability. I would also recommend taking a look at the LazyOptional class (easiest done via your IDE), since it includes a lot of documentation about why/how it is used.
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.