Bug with inheritance with var parameters

It seems the compiler (.2365) does not correctly handle inheritance with var parameters. In this code sample, I get a compile error “Parameter 1 should be var Parent” on the call to doSomething(item); even though Child is a subclass of Parent. If I remove the var marker, the code works as expected. (This is of course with the var/out compatibility flag enabled).

namespace com.matt.tests;

interface

uses
  android.app, android.content, android.os, android.view, android.widget;

type
  Parent = public class
  end;
  
  Child = public class(Parent)
  end;

type
  MainActivity = public class(Activity)
  public
    method onCreate(savedInstanceState: Bundle); override;
    method doSomething(var p: Parent);
  end;

implementation

  method MainActivity.onCreate(savedInstanceState: Bundle);
  begin
    inherited;
    // Set our view from the "main" layout resource
    ContentView := R.layout.main;
    
    var item: Child = Child.Create;
    
    doSomething(item);
  end;

  method MainActivity.doSomething (var p: Parent);
  begin
  end;
end.

com.matt.tests.zip (32.4 KB)

This is as designed. item is a Child, not a Parent. If you could pass it as var to a method that expects a Parent, that method could pass back a different type of Parent-based class into a variable that can hold only Child objects — kaboom, type safety gone.

1 Like