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

Passing List to Object Varargs to Object[]  RSS feed

 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was looking at osme code and figured out, we can pass List of any object to Objects varargs.
I looked over internet to confim this and could find any information but program confirms it.

1. List<anyObject> can be passed to Object ... args
2. List<anyObject> cannot be passed to Object[]


Example code



Can someone please explain why and how it works ?Is there some internal conversion happening?
Thanks>
 
Paul Clapham
Sheriff
Posts: 22472
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there isn't any conversion going on. What's going on is, you can pass a single Object to a parameter declared as Object... varargs. And pretty much anything is an Object. A Date is an Object. A File is an Object. A List is an Object, too! So what is passed to that parameter is just that List, and not (as you might be thinking) an array of anyObject objects.

However you can't pass a single Object to a parameter declared as Object[]. Therefore the "trick" of passing any old Object doesn't work in this case.
 
Frankely Diaz
Greenhorn
Posts: 20
Eclipse IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The method takes from 0 to n Objects, and since a List is an object i can be passed. Otherwise if the method received and Object[] args.. It means that take and Array of Objects and a single can be passed like that.

but if you have something like this, will works

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!