Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why static generic method should have<T> in front of return type  RSS feed

 
jacob deiter
Ranch Hand
Posts: 587
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why a generic static method have a in addition to return type, but a instance method not? public class Main {

public  static <T> T met(T t) {
    return t;
}

public  T met1(T t) {
    return t;
}
}
 
ramesh suri
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<T> represent the type of object. Here it is any Object can be returned. Generics can be returned for non static methods too
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, Ramesh Suri!

Jacob, the reason is quite simple - how else would you specify the generic type? Non-static methods can "inherit" the generic type from their instance, but static methods don't have an instance. But Ramesh Suri is right, non-static methods can also have a generic type of their own, also combined with the instance's generic type (as long as they have different names).
 
Stephan van Hulst
Saloon Keeper
Posts: 7812
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One such example is Stream.map(). The Stream class declares a generic type parameter T, but the map() instance method declares a second type parameter called R.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!