cluster1
cluster1

Reputation: 5674

Pass setOf as Parameter to a function. How can that be accomplished?

I have to write a function, which takes three sets as parameter.

The signatur looks this way:

fun twoInThree(a: setOf<Int>, b: setOf<Int>, c: setOf): setOf<Int> {}

But it doesn't seem possible. The compiler complains. With ArrayList it would possible theoretically.

What am I doing wrong? How can the desired declaration be accomplished?

Upvotes: 1

Views: 154

Answers (1)

Joffrey
Joffrey

Reputation: 37710

setOf() is a function, not a type. You call it to create instances of Set<T>.

When defining arguments for your custom twoInThree function, what you want is the Set<T> type instead:

fun twoInThree(a: Set<Int>, b: Set<Int>, c: Set<Int>): Set<Int> {}

Some extra notes:

  • Your confusion with ArrayList probably comes from the fact that the constructor ArrayList() (which is a function that returns an instance of ArrayList) really looks like the type ArrayList<T>.

  • Using ArrayList as the type for variables and function arguments is usually discouraged (even though it is perfectly valid). Instead, we prefer staying more general and use the List<T> interface instead.

Upvotes: 5

Related Questions