2017-02-27 180 views
7

records是流/收集和extract功能,其将数据形成这种集合的元素。科特林函数参照

是否有科特林的方式来写

records.map {extract(it)} 

没有明确地将(it)

E.g. records.map(extract)records.map {extract}

回答

10
  • 例子和R,那么你可以直接将它传递给map

    records.map(extract) 
    

    实施例:

    val upperCaseReverse: (String) -> String = { it.toUpperCase().reversed() } 
    
    listOf("abc", "xyz").map(upperCaseReverse) // [CBA, ZYX] 
    
  • 如果extract是一个顶级单个参数功能或者本地单个参数功能,可以make a function reference as ::extract并将它传递到map

    records.map(::extract) 
    

    实施例:

    fun rotate(s: String) = s.drop(1) + s.first() 
    
    listOf("abc", "xyz").map(::rotate) // [bca, yzx] 
    
  • 如果它是一个成员或类SomeClass的一个扩展函数接受任何参数或SomeClass一个属性,可以使用它作为SomeClass::extract。在这种情况下,records应包含的SomeType项目,这将被用作用于extract接收机。

    records.map(SomeClass::extract) 
    

    实施例:

    fun Int.rem2() = this % 2 
    
    listOf("abc", "defg").map(String::length).map(Int::rem2) // [1, 0] 
    
  • 由于科特林1。1,如果extract是一个成员或类SomeClass的一个扩展函数接受一个参数,可以make a bound callable reference一些接收机foo

    records.map(foo::extract) 
    records.map(this::extract) // to call on `this` receiver 
    

    实施例:

    listOf("abc", "xyz").map("prefix"::plus) // [prefixabc, prefixxyz] 
    

(runnable demo with all the code samples above)

1

你可以使用方法引用(类似于Java)。

records.map {::extract} 

采取如果extract为一些T一个功能类型(T) -> RT.() -> R的值(局部变量,属性,参数)来看看函数引用上科特林文档 https://kotlinlang.org/docs/reference/reflection.html#function-references

+4

此代码不会执行它的用途。每个'records'项目将被映射到函数引用,并且您将得到N个相同项目':: extract'的列表。 – hotkey