it doesn't. Here testFilterType just returns the e...
# getting-started
s
it doesn't. Here testFilterType just returns the entire list and has no reified logic
Copy code
getFilteredList<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()
    }
n
Copy code
fun 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 T
s
Yeah, i was trying it on an android project using 1.2.71 Kotlin
But yeah, not sure about specifying the type T with function reference
Funny thing is T is being inferred as Any?
Copy code
fun 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()
}
a
kotlin already provides
filterIsInstance(...)
s
that was just to test reified and type parameters
a
oh ok
well the problem is that
getFilteredList
expects a filter of type
List<Any?>.() -> List<Any?>
that always returns a list of
Any?
change that to
T
and it works
👍 1
s
Yeah, that does it
a
and another tip: inside
testFilterType
you don't care about what type the original List contains, so you can leave that out with
List<*>.testFilterType(): List<T>
s
Got it
Type inference at its best
Copy code
fun 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 )
}
👍 1