I would like to add a method to a built-in type (e.g. Double), so that I can use an infix operator. Is that possible?
I would like to add a method to a built-in type (e.g. Double), so
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes and no. Yes, you can make it seem like you have added a method to
double. For example:This code adds the previously-unavailable
<>operator to any object of typeDouble. So long as thedoubleToSyntaxmethod is in scope so that it could be invoked without qualification, the following will work:The ‘no’ part of the answer comes from the fact that you aren’t really adding anything to the
Doubleclass. Instead, you are creating a conversion fromDoubleto a new type which does define the method you want. This can be a much more powerful technique than the open-classes offered by many dynamic languages. It also happens to be completely type-safe. 🙂Some limitations you should be aware of:
doubleToSyntax) absolutely must be in-scope for the desired extension method to be availableIdiomatically, implicit conversions are either placed within singleton objects and imported (e.g.
import Predef._) or within traits and inherited (e.g.class MyStuff extends PredefTrait).Slight aside: ‘infix operators’ in Scala are actually methods. There is no magic associated with the
<>method which allows it to be infix, the parser simply accepts it that way. You can also use ‘regular methods’ as infix operators if you like. For example, theStreamclass defines atakemethod which takes a singleIntparameter and returns a newStream. This can be used in the following way:The
str take 5expression is literally identical tostr.take(5).