Skip to content

Fails to cast to a generic type and use generic types with v1 #183

Description

@poirierlouis

I'm having an issue when using generics with the latest preview of redscript v1.

private abstract class State {}
private class WindowState extends State {}
private class TextState extends State {}

// Issue
public func Request<T extends State>(id: Uint64) -> ref<T> {
  let state: ref<T>;
  let type = NameOf<T>();

  switch type {
    case NameOf<WindowState>():
      let window = this.FindState<WindowState>() as WindowState;
      if !IsDefined(window) {
        window = WindowState.Create(id);
      }
      state = window; // type mismatch: found `WindowState` when expected `T`
      break;
  }

  return state;
}

// Workaround
public func Request<T extends State>(id: Uint64) -> ref<T> {
  let state: Variant;
  let type = NameOf<T>();

  switch type {
    case NameOf<WindowState>():
      let window = this.FindState<WindowState>() as WindowState;
      if !IsDefined(window) {
        window = WindowState.Create(id);
      }
      state = window;
      break;
  }

  return FromVariant(state);
}

Additionally, switch-case could be avoided/simplified, though it also requires ToVariant/FromVariant tricks.

If I do:

  // ...
  let state = this.FindState<T>(id); // type mismatch: found `T` when expected `State`
  // ...
}

public func FindState<T extends State>(id: Uint64) -> ref<T> {
  if this.m_flatTree.KeyExist(id) {
    let state: ref<State> = this.m_flatTree.Get(id) as State; // from wref<IScriptable> to wref<State> to ref<State>
    // ...
    return state; // type mismatch: found `State` when expected `T`
  }

  return null;
}

If I try directly with:

    //private let m_flatTree: ref<inkHashMap>;

    let state: ref<T> = this.m_flatTree.Get(id) as T; // this type cannot be usedd with the `as` operator, the target type must be a class

Some of the issues before seems legit, but imo this last line should be working in order to be useful for methods above. Is this diagnosis error expected?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions