Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What is the Set : setOf() method in Kotlin?

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The setOf() method in Kotlin is used to create an immutable set. An immutable set is read-only and its elements cannot be modified.

Syntax

The setOf() method can be declared as shown in the code snippet below:

fun <T> setOf( vararg elements: T): Set<T>
  • elements: The elements to be added to the set.

Return value

The setOf() method returns an immutable set containing the specified elements.

Example

Consider the code snippet below, which demonstrates the use of the setOf() method.

fun main(args: Array<String>) {
val set1 = setOf("a", "b", "c")
println("set1: " + set1)
val set2 = setOf(1, 2, 3)
println("set2: " + set2)
}

Explanation

  • Line 3-4: The setOf() method is used in line 3 to create an immutable set of the three characters declared as parameters. The three characters declared as parameters are the elements of the set set1.

  • Line 6-7: The setOf() method is used in line 6 to create an immutable set of the three integers declared as parameters. The three integers declared as parameters are the elements of the set set2.

RELATED TAGS

kotlin
communitycreator

CONTRIBUTOR

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring