What is the use cases of Ignored Variable syntax in Scala?

前端 未结 3 1115
轮回少年
轮回少年 2020-12-15 10:56

According to this answer https://stackoverflow.com/a/8001065/1586965 we can do this in Scala:

val _ = 5

Now I understand the point of ignor

3条回答
  •  别那么骄傲
    2020-12-15 11:24

    The other use case (that I can think of) is related to extraction (and is called out under "Wildcard patterns" in the linked answer):

    val getCartesianPoint = () => (1, 2, 3)
    // We don't care about the z axis, so we assign it to _
    val (x, y, _) = getCartesianPoint()
    
    val regex = "(.*?)|(.*?)|?.*".r
    // Really, any unapply or unapplySeq example will do
    val regex(_, secondValue) = "some|delimited|value|set"
    

提交回复
热议问题