5

have class Klass with static method fn1

class Klass {
  static String fn1() => 'hello';
}

> Klass.fn1(); //  hello

but when Klass is assigned to a variable, calling the method fn1 fails

var k = Klass;

> k.fn1() // "Unhandled exception: Class '_Type' has no instance method 'fn1'.

don't quite know what's going on here

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
cc young
  • 15,035
  • 25
  • 76
  • 138

2 Answers2

3

I'm not sure what the intent of the code here is, but you might want to use dart:mirrors to reflectively call fn1(). I don't believe you can invoke it by assigning Klass to a variable. Here is how you can do it:

import 'dart:mirrors';

class Klass {
  static String fn1() => 'hello';
}

main() {
  final mirror = reflectClass(Klass);
  print(mirror.invoke(#fn1, []).reflectee); // Prints 'hello'.

}
Shailen Tuli
  • 11,647
  • 5
  • 33
  • 46
  • 1
    ok - will play with your suggestion. but still do not know why `Klass` and `k` are different - with everything else in Dart they are the same. – cc young Dec 27 '13 at 05:16
  • 1
    I think I'm getting it. `Klass` is a compile-time entity. to use that entity in its run-time form requires `mirror`. – cc young Dec 27 '13 at 10:58
2

A simple workaround

class Klass {
  static fn1(String name) {
    return name;
  }
  
  fn1NonStatic(String name) {
    return fn1(name);
  }
}

Klass().fn1NonStatic("test");
ITW
  • 148
  • 6