Implement a Kotlin Standard Library extension Function let:
extension KtStd<T, R> on T {
R let(R f(T it)) => f(this);
}
And write a CLI sum calculator (The problem cannot be simplified), expect:
input: 1 2 3 4 5 6 7 8 9
output: 45
input: apple 1.2 banana 3.4
output: 4.6
Then code:
main() {
stdin.readLineSync(encoding: Encoding.getByName('utf-8')).split(" ")
.map((s) => double.tryParse(s)).where((e) => e != null).fold(0, (acc, i) => acc + i)
.let((d) => d % 1 == 0 ? d.toInt() : d)
.let((it) => print(it));
}
When input 1 2 3, getting error message:
Unhandled exception:
NoSuchMethodError: Class 'double' has no instance method 'let'.
Receiver: 6.0
Tried calling: let(Closure: (dynamic) => dynamic)
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 main (file:xxx.dart:xx:xx)
#2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
In addition, if I change the fold function into reduce, giving the same input, getting error message:
Unhandled exception:
NoSuchMethodError: Class 'int' has no instance method 'let'.
Receiver: 6
Tried calling: let(Closure: (dynamic) => void)
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 main (file:xxx.dart:xx:xx)
#2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
The dart version is:
Dart VM version: 2.8.2 (stable) (Mon May 11 15:06:42 2020 +0200) on "windows_x64"
Why I got these error messages? How can I solve it?