0

I have copied full Random class from math.dart package, gave it CustomRandom name, and now I don't see why my code fails to work.

abstract class CustomRandom {
  external factory CustomRandom([int seed]);

  external factory CustomRandom.secure();

  int nextInt(int max);

  double nextDouble();

  bool nextBool();
}

I'm using it like

print("${Random().nextInt(10)}"); // standard one works
print("${CustomRandom().nextInt(10)}"); // my one fails

I know there are other things going around with standard class which isn't visible in code, but how can I make my class to work?

iDecode
  • 22,623
  • 19
  • 99
  • 186

2 Answers2

1

For customizing Random class, The external factory class must me declared somewhere else.
The main reason behind working of "Random" class is that its eternal factories are defined somewhere else, and being used in Random class.
While the reason behind not working of your "CustomRandom" class is that you are missing the implementation of your external factory "CustomRandom" anywhere.
Apparent solutions:
1) Keep class name CustomRandom but keep external factory name unchanged same as "Random" class.
2) Create own external factory and use here.

Sanket Vekariya
  • 2,848
  • 3
  • 12
  • 34
  • Thanks, can you please tell me how can I create my external factory (your solution #2)? – iDecode Apr 18 '20 at 06:27
  • As this is a part of the math library, you have to copy the entire math library, or you have to code inside the math library. I have been in a math library for a while and found it important. check out: https://stackoverflow.com/questions/53886304/understanding-factory-constructor-code-example-dart – Sanket Vekariya Apr 18 '20 at 06:47
1

Your version won't do anything because it has no implementation.

The real Random class has an external factory constructor (whose implementation lives elsewhere, one for the Dart VM/runtime, one for JavaScript) and that implementation instantiates an object that actually does something.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204