1

Im new to scala and I've been looking everywhere for how to find how to structure my file I write with my function in it. Furthermore how to call that function from cmd. I'm trying to write a simple function like just to understand how to get started writing programs. Anything simple like the below would be useful.

def test (n : Int){ println(n + n) }

Keep in mind i am writing this in Notepadd ++. my first assignment is the gray code. So my ultimate goal is to figure out how files are run and functions are called. There are tons of solutions to gray code below is 1.

def gray(n: Int) ={
def gray(n: Int, res: List[String]): List[String] = {
     val nRes = res.map("0" + _) ::: res.reverse.map("1" + _)
         if(n == 1) nRes
           else gray(n-1, nRes);
    }
   gray(n, List(""))
}

Things i've tried were to make an object file and running that and parsing the args to pass to a function.

object test1 {
   def main(args: String) {
     n = args.toInt
  test(n);
}
def test(n: Int){
    println( n + n)
    }
}

2 Answers 2

3

test1 is missing a val declaration for n = args.toInt. Adding that gives the code below which compiles ok.

object test1 {
  def main(args: String) {
    val n = args.toInt
    test(n);
  }
  def test(n: Int){
   println( n + n)
  }
}

Loading this in the REPL will show defined module test1. Then you can call test1.main("1") which calls test and prints out 2. If you're not familiar with the REPL, see this link.

scala> :load Test1.scala
Loading Test1.scala...
defined module test1

scala> test1.main("1")
2
Sign up to request clarification or add additional context in comments.

Comments

0

I actually figured it out after playing around with it alittle more. The solution is as simple as Console.readInt. That grabs what ever value was entered by the user into the console.

object project1{
def main(args: Array[String]) {
println("Hello World")
println("Enter a number")

val x = Console.readInt

test(x);
 // println(x)
}
def test(x: Int){
    println( x + x)
    }
}

when on the console you simply have to type scale project1.scala at which point the function runs and its like you were using java or C++ and the value is taken from the screen when you enter a key.

so the above console would look like.

Desktop/> scala helloWorld.scala

Hello World
Enter a number
3
6

1 Comment

You didn't mention reading from the console in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.