spebbe / dartz

Functional programming in Dart
MIT License
749 stars 60 forks source link

_TypeError (type 'Uint8List' is not a subtype of type 'Never' of 'k') #122

Open huzaifansari54 opened 1 year ago

huzaifansari54 commented 1 year ago

@spebbe hello i want to create Imap of <Unit8List ,XFile > i kindly help me out error

tcmhoang commented 1 year ago

In order to create IMap<K,V> using imap function, the key's type must extend Comparable. And Uint8List type does not satisfy this condition.

And you may wonder why the compiler did not catch this error before running. The reason is that you gave the type signature of both key and value pair in the variable definition, so the compiler infers the right expression's type. So it casts the rights' expression type from <dynamic,dynamic> to be the exact same specified type in signature. In your case, it will be <Uint8List,XFile>.

It cast in the runtime rather than complied time due to the nature of the comparableOrder function implementation which is used in imap function. It does not force you to specify the A type in the Comparable<A> type, again it will be Compable<dynamic> and it will be cast down during runtime. First, it will happily create an instance of this type for you, but later errors will definitely occur when interacting with the instance of this type.

Also, the IMap type definition does not enforce this kind of constrain. Because it assumes you specify the order when you're creating an instance of IMap

In order to achieve what you want, you need to use the constructor of IMap and explicitly specify the Order of the key in IMap.

You may implement something like this.

IMap<Uint8List, dynamic> a = IMap.empty(
    orderBy(IntOrder, (a) => a.hashCode),
);
huzaifansari54 commented 1 year ago

thanks sir