![]() ![]() Think of the unapply method as being the opposite of the apply method of a companion object. Val result = Fraction(3, 4) * Fraction(2, 5)Īn extractor is an object with an unapply method. That sounds like a small thing, but if you have many Fraction values, it is a welcome improvement: For example, consider a Fraction class.ĭef apply(n: Int, d: Int) = new Fraction(n, d)īecause of the apply method, we can construct a fraction as Fraction(3, 4) instead of new Fraction(3, 4). The apply method is also commonly used in companion objects to construct objects without calling new. Val bobsScore = scores("Bob") // Calls scores.apply("Bob") This mechanism is used in arrays and maps. ) = valueĬorresponds to the call f.update(arg1, arg2. Unless it occurs to the left of an assignment. If f is not a function or method, then this expression is equivalent to the call f.apply(arg1, arg2. Scala lets you extend the function call syntax f(arg1, arg2. Part 1: The Apply and Update Methods for Scala Match Horstmann's introductory Scala book, Scala for the Impatient. The content in this tutorial is taken from ProTech's Scala Courseware, which is a collaboration with Pearson Education, Inc. This will provide us with the necessary context to talk about some even cooler features (pattern matching and case classes) in Part 2. In Part 1, we begin by talking about something called apply and update. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |