Getting Started 부터

2016. 5. 27. 16:24Other languages & Web programming/Scala


처음에 얼마만큼의 매력을 보이는 것이 중요할듯..
함수형 프로그래밍으로 들어가보도록 합시다.




스칼라를 배우는 최고의 길은 여러분이 이미 알고  있는 것 과 여러분이 일을 배우는 것에 대해 선호하는 법에 따라 달라집니다.
책,튜토리얼, 코스 트레이닝, 프리젠테이션 그리고 물론 연습을 위한 Scala 컴파일러를 포함한 가능한 다양한 리소스들이 있습니다. 
멋진 조화를 찾는 많은 분들은 손에 Scala 책들중 하나를 가지고 있고, Scala 컴파일러를 가지고 예제를 바로 시작하는 것입니다. 
그와는 다르게, 여러분은 Scala 트레이닝 코스 또는 온라인에서 가능한 것을 사용하여 시작하길 바랄지도 모르죠

Scala 지식이 늘어감에 따라, 여러분은 좀 더 향상된 것과 여러분에게 쉽게 도움을 주는 매우 친근한 Scala 커뮤니티가 있다는 것을 알게 될것입니다.
커뮤니티에 모든분들은 Scala에 대한 열정을 공유하고, 새로운분들을 따뜻하게 맞이해 줍니다.
프로그래머들에게 새로운 Scala에 작성된 많은 도움되는 것들은 , 산뜻한 새로운 기술이나 향상된 요건들 또는 일부 Scala 포럼이나 개인적인 블로그들중 하나에 툴들 도움을 위해 요청한 이메일에 대해 답할 것입니다.

프로그램 초보자들을 위한 Scala

여러분이 어떻게 코딩하는지 배우고자 시작한다면, 여러분은 Scala에 관한 큰 구성 요소들이 여러분이 몇가지 프로그래밍 경험을 이미 가지고 있다고 가정한다는 것을 알게 될것입니다. 
우리가 여러분에게 Scala의 세상으로 직접 체험 할수 있는 프로그래밍 초보자를 위해 추천 할수 있는 두개의 값진 리소스들이 있습니다. 

- 스칼라에서의 함수형 프로그래밍 원칙 온라인 강의, coursera에서 확인할수 있습니다.
   스칼라 창시자인, 마틴 오더스키가 진행하는 이 온라인 강의는 함수형 프로그래밍의 기초를 익히는, 아카데믹한 성취를 얻을수 있답니다. 
   여러분은 스칼라에 대해 많은 것을 프로그래밍 문제들을 풀면서 배울수 있을 것입니다.

 - Kojo는 Scala 탐구하고 수학,예술,음악, 애니메이션과 게임을 가리고 놀기 위한 프로그래밍을 사용하는  양방향 러닝 환경입니다. 

여러분의 첫번째 코드 라인

"Hello, World" 프로그램

첫번째 예제로, 우리는 표준 "hello,world!" 프로그램을 사용합니다.  스칼라툴을 사용하는 것을 설명하기 위해서요, 이 언어에 대해 너무 많이 알 필요 없이말이죠.

object HelloWorld{
     def main(args: Array[String]): Unit = {
          println("Hello, World!")
     }
}

이 프로그램 구문은 Java 프로그래머들에게 친근할 것입니다 : 그건 메소드 main 으로 구성되어 있습니다. 친근하게 인사하는 것을 출력하는 것을 표준 출력에 
스칼라 프로그램이랑 환경이 제대로 맞춰졌다고 가정할 것 입니다.


쌍방향으로 가동해

"scala" 명령은 scala 표현식들이 쌍방향으로  해석되어지는 곳인 상호작용 쉘을 시작합니다.

> scala
   This is a Scala shell.
   Type in expressions to have them evaluated.
   Type :help for more information.

scala> object HelloWorld{
   |       def main(args: Array[String]): Unit = {
   |         println("Hello, World!")
   |       }
   |  }
defined module HelloWorld

scala> HelloWorld.main(Array())
Hello, world!

scala>:q
>

나갈때는 :q 단축키를 사용하면 되옵니다.


컴파일

"scalac" 명령어는 스칼라 소스 코드를 컴파일 하고, Java 바이트코드를 생성합니다. 그건 어느 표준 JVM하에서 실행되어질수 있습니다.
스칼라 컴파일러는 javac와 비슷하게 동작합니다. Java SDK의 자바 컴파일러

scalac HelloWorld.scala

보통 scalac는 클래스 파일들을 현재 동작하는 디렉토리에 생성합니다.
여러분은 다른 아웃풋 디렉토리를 -d 옵션을 사용해서 명시할수도 있습니다.

>scalac -d classes HelloWorld.scala

실행해 

스칼라 명령은 생성된 바이트코드를 적당한 옵션과 함께 실행합니다.

>scala HelloWorld

"scala" 는 명령옵션을 명시하는 것이 가능합니다. 예를 들명 -classpath 옵션은 :

>scala -cp classes HelloWorld

scala 명령의 인자는 상위 레벨 객체이 어야만 합니다.
저 객체가 App 특성(trait)을 상속했다면, 그땐 모든 구문에는 그 객체가 실행되어 질것이라는 것이 포함되어야 합니다.
그렇지않으면 여러분은 프로그램의 진입점으로 행동할 메인 메소드를 추가해야 합니다.

"Hello,World!" 예제가 App 특성을 사용한 것과 같이 보이는 방법입니다.


object HelloWorld extends App {
    println("Hello, World!")
}

스크립트

우리는 또한 우리 예제를 쉘 스크립트나 배치 명령으로 가동시킬지도 모릅니다.( scala 명령의 메인 페이지에 예제를 보면)
아래 스칼라 코드를 포함하는  bash shell script "script.sh"

#!/bin/sh
exec scala "$0" "$@"
!#
object HelloWorld extends App{
    println("Hello, World!")
}
HelloWorld.main(args)

커맨드 쉘에서 바로 실행할수 있습니다.

>./script.sh

참고
파일 "script.sh"는 실행 접근권한과 PATH 환경변수에 명시되어진 scala 명령어를 위한  search path을 가지고 있다라고 가정합니다.



GETTING STARTED


The best  way to learn Scala depends on what you know already and the way you prefer to learn things.
There is a variety of resources available including books, tutorial, training courses, presentations, and of course the Scala compiler for practice.
Many people find a good combination is to have one of the Scala books at hand and to start right away trying the examples with the Scala Compiler.
On the other hand, you may want to get started with a Scala training course or using the material available online.

As your knowledge of Scala grows, you will find there is more advanced material and a very friendly Scala community at ahnd to help you.
They all share a passion for Scala and welcome newcomers warmly.

Many have written helpful material for programmers new to Scala, will respond to emails asking for help or are sharing neat new techiques, advanced concepts or tools in one of several Scala forums or personal blogs.

Scala for Programming Beginners

If you are just starting to learn how to code, you will find that a large portion of the material about Scala assumes that you already have some programming experience.

There are two valuable resources which we can recommend to programming beginner that will take you directly into the world of Scala :

- The online class Functional Programming Principles in Scala , available on coursera.
   Taught by the creator of Scala, Martin Odersky, this online class takes a somewhat academic approach to teach the fundamentals of functional programming.
  You will learn a lot of Scala by solving the programming assignments.

- Kojo is an interactive learning enviornment that uses Scala programming to explore and play with math , art, music , animations and games.


Your first lines of code

The "Hello, world!" Program

As a frist example, we use the standard "Hello, World!" program to demonstrate the use of the Scala tools without knowing too much about the language.

object HelloWorld{
     def main(args: Array[String]): Unit = {
          println("Hello, World!")
     }
}

The structure of this program should be familiar to Java programmers: it consists of the method main which prints out a friendly greeting to the standard output.

We assume that both the Scala software and the user environment are set up correctly. 
for Example : 

Run it interactively!

The scala command starts an interactive shell where Scala expressions are interpreted interactively.

> scala
   This is a Scala shell.
   Type in expressions to have them evaluated.
   Type :help for more information.

scala> object HelloWorld{
   |       def main(args: Array[String]): Unit = {
   |         println("Hello, World!")
   |       }
   |  }
defined module HelloWorld

scala> HelloWorld.main(Array())
Hello, world!

scala>:q
>

The shortcut :q stands for the internal shell command :quit used to exit the interpreter.

Compile it!

The scalac command compile one (or more) Scala source file(s) and generates Java bytecode which can be executed on any standard JVM.
The Scala compiler works similarly to javac, the Java compiler of the Java SDK.

scalac HelloWorld.scala

By default scalac generates the class files into the current working directory.
You may specify a different output directory using the -d option.

>scalac -d classes HelloWorld.scala

Execute it!

The scala command executes the generated bytecode with the appropriate options:

>scala HelloWorld

scala allows us to specify command options, such as the -classpath (alias -cp) option :

>scala -cp classes HelloWorld

The argument of the scala command has to be a top-level object.
If that object extends trait App, then all statement contained in that object will be executed; otherwise you have to add a method main which will act as the entry point of your program.

Here is how the "Hello, World!" example look like using the App trait:


object HelloWorld extends App {
    println("Hello, World!")
}


Script it!

We may also run our example as a shell script or batch command (see the example in the man pages of the scala command).

The bash shell script "script.sh" containing the following Scala code (and shell preamble)

#!/bin/sh
exec scala "$0" "$@"
!#
object HelloWorld extends App{
    println("Hello, World!")
}
HelloWorld.main(args)

can be run directly from the command shell:

>./script.sh

Note: We assume here that the file script.sh has execute access and the search path for the scala command is specified in the PATH environment variable.