Reputation: 225
I had 2 functions that does basically the same thing, so I thought to create an extension function.
The problem is that I need to extract the data of each class in order to get the correct result, I thought of creating a Generic function, and inside this function decide which class member to access inside when
statement.
But when I try to call T
inside the when statement, I'm getting Type parameter 'T' is not an expression
What am I doing wrong?
My function:
fun <T: Any> List<T>.extractWithSepreation(errorString: String): String {
var errorString = "There is no available $errorString"
if (this.isEmpty()) {
return errorString
}
errorString = ""
this.forEachIndexed { index, item ->
when(T)
}
}
Upvotes: 1
Views: 858
Reputation: 31438
The error message pretty much says it all. T
is not an expression, so it cannot be used inside when(...)
. T
just refers to the class of the item
of the List
.
Didn't you mean using something like:
when(item) {
is ClassA -> doSomething()
is ClassB -> doSomethingElse()
}
?
Upvotes: 3