I have created a below syntax to get a list of values. def primeNum(n:Int) = (1 to 1000).filter(i =>i % 2 !=0 && (i > 2))
I am trying to get dynamically value from the result if I pass i/p n to any value(if n = 5 i need to get 5th value from result. If I pass n=7 i need to get 7th position value)
I am not able to get how to pass make it dynamically based based on input value.
Can some suggest.
Howdy! I believe you are looking for the apply() function, which is simply expressed as parentheses in Scala – that returns the nth value in a sequence. See for example this fiddle:
def chosen(i: Int) = (10 to 20)(i)
println(chosen(5))
> 15
The suggestion was to Google it, and you were asked what you had already researched / Googled… you didn’t respond, you just came back asking for an answer again. I think you would get more useful responses if you spent some time explaining what you’ve already tried to solve the problem on your own, so that we know the right direction in which to point you.
You are getting a lot of feedback on how to use the language; if you need information on how to identify prime numbers, there are well-known, language-agnosticn algorithms available; which one you choose depends on how your implementation will be used, which is what makes it so hard for us to help you without having more context around how you will be using this in a production code base.
Are you asking for interactive input from the user? If so, I wrote the following little function that prompts the user for a value. For convenience, it provides a default value that the user can select by simply hitting return.
def enter( // prompt user to enter input
label: String = "", // label for requested input
default: String = ""): // default value to return if nothing entered
String = {
print("enter " + label + " [" + default + "]: ")
val entry = scala.io.StdIn.readLine
if (entry == "") default else entry
}
def stop() = { // breakpoint for debugging
print("\nhit <enter> to continue ")
scala.io.StdIn.readLine
()
}
Here is an example usage:
val number = enter("number", 2).toInt
Note that it returns a String, which must be converted to the required type.