Sam
09/26/2018, 10:28 PMgetFilteredList<Int>( list, List<Any?>::testFilterType )
private fun <T> List<Any?>.testFilterType() : List<Any?> {
val filteredList = mutableListOf<Any?>()
forEach {
filteredList.add( it )
}
return filteredList
}
private fun <T> getFilteredList( list : List<Any?>, filter : List<Any?>.() -> List<Any?> ) : List<Any?> {
return list.filter()
}
Nikky
09/26/2018, 10:38 PMfun main(args: Array<String>) {
val list = listOf(1, 2, 3)
getFilteredList<Int>( list, List<Any?>::testFilterType )
}
private inline fun <reified T> List<T>.testFilterType() : List<T> {
val filteredList = mutableListOf<T>()
forEach {
filteredList.add( it )
}
return filteredList
}
private fun <T> getFilteredList( list : List<Any?>, filter : List<Any?>.() -> List<Any?> ) : List<Any?> {
return list.filter()
}
this seems to compile, due to the expected return type T can get resolved, otherwise i have no clue how to specify TSam
09/26/2018, 10:44 PMfun main(args: Array<String>) {
val list = listOf( 1, 2, 3, "One", "Two", "Three" )
val newList = getFilteredList<Int>( list, List<Any?>::testFilterType )
println( newList )
}
private inline fun <reified T> List<Any?>.testFilterType() : List<T> {
val filteredList = mutableListOf<T>()
forEach {
if( it is T ) {
filteredList.add( it )
}
}
return filteredList
}
private fun <T> getFilteredList( list : List<Any?>, filter : List<Any?>.() -> List<Any?> ) : List<Any?> {
return list.filter()
}
Andreas Sinz
09/26/2018, 11:00 PMfilterIsInstance(...)
Sam
09/26/2018, 11:01 PMAndreas Sinz
09/26/2018, 11:04 PMgetFilteredList
expects a filter of type List<Any?>.() -> List<Any?>
that always returns a list of Any?
change that to T
and it worksSam
09/26/2018, 11:08 PMAndreas Sinz
09/26/2018, 11:09 PMtestFilterType
you don't care about what type the original List contains, so you can leave that out with List<*>.testFilterType(): List<T>
Sam
09/26/2018, 11:09 PMfun main(args: Array<String>) {
executeFunction( "12345", 12345, String::printParameter )
}
private fun <T> String.printParameter( value : T ) {
println( "$this $value" )
}
private fun <T> executeFunction( string : String, parameter : T, block : String.(T) -> Unit ) {
string.block( parameter )
}