Dart type castings

2019-09-16 20:23发布

问题:

I try to implement mergeSort in dart. Here is my code:

    List mergeSort(List list)
    {
        if (list.length <= 1) return list;
        List left, right, result;
        int middle = list.length ~/ 2;

        left = mergeSort(list.getRange(0, middle));
        right = mergeSort(list.getRange(middle, list.length) as List);

        result = merge(left, right);
        return result;
    }

And I get an TypeError at this line:

        left = mergeSort(list.getRange(0, middle));   

It seems that getRange() returns Iterable, but List implements Iterable what is the problem here, shouldn't it work?

Anyway when I try:

            left = mergeSort(list.getRange(0, middle) as List);

it still doesn't work and gives me a CastError. So my question is what's the problem here, and what's the Dart-style solution for it? Thx in advance.

回答1:

Iterable.toList() should do the trick.

 left = mergeSort(list.getRange(0, middle).toList());

You can't directly cast an Iterable to a List because Iterable is a super type of List. You can cast an object to its parent class, but you cant cast an object to any of its child class.

Example:

var a = new AnyClass();
var o = new Object(); //Actually this is not correct, but let's imagine

(o as AnyClass).toString() //wont works
(a as Object).toString() //will works


回答2:

The getRange method returns an Iterable, not a List. Using as List does not change that, it just fails because its operand isn't actually a List.

You can use the List.sublist method to get a slice of a list as an actual List.

The collection package on pub also contains an implementation of merge-sort: package:collection/algorithms.dart.



标签: dart