Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a declare a Supplier in Kotlin?

Tags:

kotlin

I want to use a Supplier interface in my tests. I have mocked it right now as a crude soln, but how do i define it ? In Java I would do something like ,

Supplier<List<String>> list = () -> Collections.emptyList();

is there a way to define it like this in kotlin as well?

like image 906
Denise Avatar asked Oct 16 '25 16:10

Denise


1 Answers

In Kotlin, functional objects are first class so you don't need Supplier to create a function that produces something unless you're working with a Java API that demands it. The functional equivalent of a Supplier would be a function that has no inputs and returns something, so you'd define it like this:

val list: ()->List<String> = { emptyList() }

If you need a literal Supplier, you can use the constructor-like "adapter function" SAM-conversion lambda syntax:

val list: Supplier<List<String>> = Supplier { emptyList() }
like image 196
Tenfour04 Avatar answered Oct 18 '25 06:10

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!