Is it possible to initialize a class parameter with a function in Scala?
Example:
def square(x: Int) = x*x
class Foo(val x: Int = square(x))
This doesn’t compile but I hope you get the idea.
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.
Hard to guess what you’re trying to achieve, but let me have a go:
Note that if you try this in the REPL, you must enter both the class and its companion object at the same time (in paste mode, via
:pa), or theobject Foowon’t have access to the private class constructor.This applies the
squarefunction to the parameterxbefore creating aFooinstance: