Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Kotlin in Action: example Inline with higher order function  RSS feed

 
Ranch Hand
Posts: 472
8
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack Wharton did this example on why to use  Inline in high order functions but I cannot grasp it

inline fun <T>   List<T>.filter(predicateT) ->Boolean):List<T>{
//..
}



I do not get
1) the meaning of <T>  after fun. It looks redundant to me, of course it takes a <T> and returns a List<T>
2) why there is inline. which advantage i get from that? say JW normally this lambda will have to allocate an anonymous class,
but because the function body is inlined you can basically get rid of this anonymous class all togheter

Could you give me some example please

 
author
Ranch Hand
Posts: 149
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The <T> is necessary to declare a type parameter. This is required because every name in the source code needs to be declared somewhere. For example, if a function returns a List<String>, there is a String class declared somewhere (in the Kotlin standard library), and the declaration refers to it. In this case, there is no class named T, so you need to specify what T is. You do so by declaring T as a type parameter: fun <T> filter(...)

The advantage is exactly what JW says; I'm not sure what other example you need. You get a program which has fewer classes, fewer methods and runs faster.
 
Giovanni Montano
Ranch Hand
Posts: 472
8
Android Open BSD Slackware
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dmitry Jemerov wrote:The <T> is necessary to declare a type parameter. This is required because every name in the source code needs to be declared somewhere. For example, if a function returns a List<String>, there is a String class declared somewhere (in the Kotlin standard library), and the declaration refers to it. In this case, there is no class named T, so you need to specify what T is. You do so by declaring T as a type parameter: fun <T> filter(...)

The advantage is exactly what JW says; I'm not sure what other example you need. You get a program which has fewer classes, fewer methods and runs faster.


got it thanks
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!