https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tianyu Zhu

04/15/2022, 9:47 PM
I would like to write something like this:
Copy code
fun test(foo: List<Number>) {
  if (foo.containsOnly<Int>()) {
    val bar: List<Int> = foo
  }
}
Note that I don't want to use
filterIsInstance()
here. Is it possible to write an extension function that allows for this smart-cast?
m

MR3Y

04/16/2022, 12:21 AM
have you tried?:
Copy code
inline fun <reified T: Number> List<Number>.containsOnly(): Boolean {
    contract {
        returns(true) implies this is List<T>
    }
    forEach {
        if(it !is T) return false
    }
    return true
}
t

Tianyu Zhu

04/16/2022, 12:46 AM
I tried that but the compiler complains about
this is List<T>
because
List<T>
contains an erased type
5 Views