Sam Schilling
01/21/2020, 4:58 PMopen class Animal { ... }
// Using upper bound generic
fun <T: Animal> print(animal: T) { ... }
// Using type directly
fun print(animal: Animal) { ... }
It seems in both cases any subclasses of Animal
will work with the function call. In which case the second option seems more readable and condensed if they function identically.streetsofboston
01/21/2020, 5:01 PMstreetsofboston
01/21/2020, 5:02 PMSam Schilling
01/21/2020, 5:02 PMfun <T: Comparable<T> foo() { … }
?streetsofboston
01/21/2020, 5:02 PMfun <T: Animal> print(animal: T, callback: (T) -> Unit) { … }
does make a differenceSam Schilling
01/21/2020, 5:03 PMstreetsofboston
01/21/2020, 5:03 PMit
parameter of your lambda will have the same sub-type of animal as the argument value for animal
Sam Schilling
01/21/2020, 5:04 PMstreetsofboston
01/21/2020, 5:05 PMSam Schilling
01/21/2020, 5:09 PMfun <T: Comparable<T>> sort(list: List<T>) { ... }
Which would be identical to:
fun <T> sort(list: List<Comparable<T>>) { ... }
Casey Brooks
01/21/2020, 5:22 PMlistOf<Comparable<String>>()
is actually not compatible with the first example, since Comparable<String>
itself does not implement Comparable<Comparable<String>>
. And this is actually a good thing, since you should not sort a list by casting or wrapping it with a Comparable
, but instead provide the sort function with a Comparator
Sam Schilling
01/21/2020, 5:25 PMCasey Brooks
01/21/2020, 5:32 PMComparable
which “wrap” sortable objects. And you can’t really get the sorted objects back from the second without casting, which may not be a valid assumption if it is an actual wrapper object instead of being implemented as an interfaceE.Kisaragi
01/21/2020, 6:35 PMRay Eldath
01/22/2020, 7:28 AMstreetsofboston
01/22/2020, 12:09 PMfun <T : View> findViewById(id: Int) : T
and then val nameField: TextView = findViewById(R.id.name)
.Sam Schilling
01/22/2020, 4:43 PM