February 2020
Intermediate to advanced
412 pages
9h 36m
English
cast() is a simple, map-like operator that casts each emitted item to another type. If we need to cast each value emitted by Observable<String> to an Object (and return an Observable<Object>), we could use the map() operator as shown in the following example:
Observable<Object> items = Observable.just("Alpha", "Beta", "Gamma") .map(s -> (Object) s);
Instead, we can use the more specialized shorthand cast(), and simply pass the class type we want to cast to, as shown in this code snippet:
Observable<Object> items = Observable.just("Alpha", "Beta", "Gamma") .cast(Object.class);
If you find that you are having typing issues due to inherited or polymorphic types being mixed, this is an effective brute-force way to cast everything down ...
Read now
Unlock full access