├── .gitignore ├── Makefile ├── README.rst ├── _templates └── layout.html ├── changelog.rst ├── conf.py ├── control_structures ├── comprehensions.rst ├── curly_braces.rst ├── index.rst └── trivial_conditionals.rst ├── declarations ├── fields.rst ├── function_values │ ├── multi_expression_functions.rst │ └── spacing.rst ├── index.rst ├── methods.rst ├── methods │ ├── currying.rst │ ├── higher_order_functions.rst │ └── modifiers.rst └── ordering.rst ├── files ├── index.rst └── multi_unit_files.rst ├── indentation ├── index.rst ├── line_wrapping.rst └── methods_with_numerous_arguments.rst ├── index.rst ├── make.bat ├── method_invocation ├── arity0 │ ├── index.rst │ └── suffix_notation.rst ├── arity1 │ ├── higher_order_functions.rst │ └── index.rst ├── index.rst └── operators.rst ├── naming_conventions ├── annotations.rst ├── classes_traits.rst ├── fields.rst ├── index.rst ├── methods │ ├── accessors_mutators.rst │ ├── index.rst │ ├── operators.rst │ └── parentheses.rst ├── objects.rst ├── packages.rst ├── special_note_on_brevity.rst ├── type_aliases.rst └── type_parameters │ ├── higher_kinds.rst │ └── index.rst ├── nested_blocks ├── curly_braces.rst ├── index.rst └── parentheses.rst ├── overview.rst ├── refcard.rb ├── scaladoc └── index.rst └── types ├── annotations.rst ├── ascription.rst ├── functions ├── arity_1.rst └── index.rst ├── index.rst ├── inference ├── function_values.rst ├── index.rst └── void_methods.rst └── structural_types.rst /.gitignore: -------------------------------------------------------------------------------- 1 | *.sw? 2 | .buildinfo 3 | .DS_Store 4 | ScalaStyleGuide.html 5 | ScalaStyleGuide.pdf 6 | index.html 7 | *.tex 8 | *.aux 9 | *.log 10 | *.out 11 | *.dvi 12 | /_build/ 13 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | COPY = cp 10 | CD = cd 11 | TGZ = tar cvfz 12 | TGZ_EXT = tgz 13 | CMD_SEP = ; 14 | DIR_UP = ../ 15 | 16 | # Internal variables. 17 | PAPEROPT_a4 = -D latex_paper_size=a4 18 | PAPEROPT_letter = -D latex_paper_size=letter 19 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 20 | 21 | .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest pdf ps package 22 | 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " package create the HTML and PDF suitable for putting on github pages" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 33 | @echo " pdf to make a PDF file, you can set PAPER=a4 or PAPER=letter" 34 | @echo " changes to make an overview of all changed/added/deprecated items" 35 | @echo " linkcheck to check all external links for integrity" 36 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 37 | @echo " package package everything up to put up on github pages" 38 | 39 | clean: 40 | -rm -rf $(BUILDDIR)/* 41 | 42 | package : html pdf 43 | $(COPY) $(BUILDDIR)/latex/ScalaStyleGuide.pdf $(BUILDDIR)/html 44 | $(CD) $(BUILDDIR)/html $(CMD_SEP) $(TGZ) $(DIR_UP)$(DIR_UP)ScalaStyleGuide.$(TGZ_EXT) . 45 | 46 | html: 47 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 48 | @echo 49 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 50 | 51 | dirhtml: 52 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 53 | @echo 54 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 55 | 56 | pickle: 57 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 58 | @echo 59 | @echo "Build finished; now you can process the pickle files." 60 | 61 | json: 62 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 63 | @echo 64 | @echo "Build finished; now you can process the JSON files." 65 | 66 | htmlhelp: 67 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 68 | @echo 69 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 70 | ".hhp project file in $(BUILDDIR)/htmlhelp." 71 | 72 | qthelp: 73 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 74 | @echo 75 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 76 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 77 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ScalaStyleGuide.qhcp" 78 | @echo "To view the help file:" 79 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ScalaStyleGuide.qhc" 80 | 81 | latex: 82 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 83 | @echo 84 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 85 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 86 | "run these through (pdf)latex." 87 | 88 | changes: 89 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 90 | @echo 91 | @echo "The overview file is in $(BUILDDIR)/changes." 92 | 93 | linkcheck: 94 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 95 | @echo 96 | @echo "Link check complete; look for any errors in the above output " \ 97 | "or in $(BUILDDIR)/linkcheck/output.txt." 98 | 99 | doctest: 100 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 101 | @echo "Testing of doctests in the sources finished, look at the " \ 102 | "results in $(BUILDDIR)/doctest/output.txt." 103 | 104 | 105 | pdf: latex 106 | $(MAKE) -C _build/latex all-pdf 107 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | この文書について 2 | ============== 3 | 4 | この文書はScala Style Guideの日本語訳です。なにはともあれ公開します。 5 | 6 | 成果物 7 | ===== 8 | 9 | * オンライン - http://yanana.github.com/scala-style 10 | 11 | ※PDF生成にpdflatexを使っているので,PDF生成できていません… 12 | 13 | Read It 14 | ======= 15 | 16 | * online - http://davetron5000.github.com/scala-style 17 | * PDF - http://davetron5000.github.com/scala-style/ScalaStyleGuide.pdf 18 | 19 | Build It 20 | ======== 21 | 22 | Get Set Up 23 | ---------- 24 | 25 | * Sphinx - ``easy_install sphinx`` 26 | * github-tools - ``easy_install github-tools`` 27 | * LaTeX (specifically ``pdflatex``) 28 | 29 | Make it 30 | ------- 31 | 32 | * ``make html # open _build/html/index.html`` 33 | * ``make pdf # open _build/latex/ScalaStyleGuide.pdf`` 34 | 35 | Note if you are on Windows, there is a ``make.bat`` that allegedly does this, but I have no clue if it does. 36 | 37 | Also note that the majority of the ``Makefile`` was generated by Sphinx. 38 | 39 | Fork It 40 | ======= 41 | 42 | * Make a clone 43 | * Make some changes 44 | * Push the changes 45 | * Send me a pull request 46 | 47 | Note that this document is still in flux, so I would recommend discussing your changes on 48 | ``scala-user@listes.epfl.ch`` or ``scala@listes.epfl.ch`` to try get some community consensus 49 | -------------------------------------------------------------------------------- /_templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | 3 | {% block sidebarsourcelink %} 4 | {{ super() }} 5 |

別のフォーマット

6 | 9 |

貢献

10 | 13 | {% endblock %} 14 | -------------------------------------------------------------------------------- /changelog.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 5 | **v1.2.5** - 4/13/2011 6 | * Expanded multiple-parameter list styles to include formatting for long parameter lists 7 | * Added a changelog 8 | 9 | **v1.2.4** - 2/13/2011 10 | * Reworked the currying section to be about multiple parameter lists, based on community feedback 11 | 12 | **v1.2.3** - 1/2/2011 13 | * Reworded bit about short parameter names based on community feedback 14 | 15 | **v1.2.2** - 12/30/2010 16 | * Spelling mistakes 17 | 18 | **v1.2.1** - 10/2/2010 19 | * Removing special note about IntelliJ that no longer applies 20 | * Slight cleanup of scaladoc section and added an example for object scaladoc 21 | 22 | **v1.2.0** - 10/2/2010 23 | * Clarified how packages work in light of Scala 2.8 24 | * Added new section on writing scaladoc 25 | 26 | **v1.1.0** - 1/26/2010 27 | * Clarified the use for ``for`` comprehensions 28 | * Documented avoidance of ``/:`` and similar operators 29 | * Possibly other changes 30 | 31 | **v1.0.0** 32 | * Similar to Daniel Spiewak's initial version; possibly slight changes 33 | -------------------------------------------------------------------------------- /conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Scala Style Guide documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Nov 15 17:04:09 2009. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.append(os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # Add any Sphinx extension module names here, as strings. They can be extensions 24 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 25 | extensions = ['github.tools.sphinx'] 26 | 27 | # Add any paths that contain templates here, relative to this directory. 28 | templates_path = ['_templates'] 29 | 30 | # The suffix of source filenames. 31 | source_suffix = '.rst' 32 | 33 | # The encoding of source files. 34 | #source_encoding = 'utf-8' 35 | 36 | # The master toctree document. 37 | master_doc = 'index' 38 | 39 | # General information about the project. 40 | project = u'Scala Style Guide' 41 | copyright = u'2009, Scala Community' 42 | 43 | # The version info for the project you're documenting, acts as replacement for 44 | # |version| and |release|, also used in various other places throughout the 45 | # built documents. 46 | # 47 | # The short X.Y version. 48 | version = '1.2' 49 | # The full version, including alpha/beta/rc tags. 50 | release = '1.2.5' 51 | 52 | # The language for content autogenerated by Sphinx. Refer to documentation 53 | # for a list of supported languages. 54 | #language = None 55 | language = 'ja' 56 | 57 | # There are two options for replacing |today|: either, you set today to some 58 | # non-false value, then it is used: 59 | #today = '' 60 | # Else, today_fmt is used as the format for a strftime call. 61 | #today_fmt = '%B %d, %Y' 62 | 63 | highlight_language = 'scala' 64 | 65 | # List of documents that shouldn't be included in the build. 66 | unused_docs = ['README', 'ScalaStyleGuide'] 67 | 68 | # List of directories, relative to source directory, that shouldn't be searched 69 | # for source files. 70 | exclude_trees = ['_build','chapters'] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all documents. 73 | #default_role = None 74 | 75 | # If true, '()' will be appended to :func: etc. cross-reference text. 76 | #add_function_parentheses = True 77 | 78 | # If true, the current module name will be prepended to all description 79 | # unit titles (such as .. function::). 80 | #add_module_names = True 81 | 82 | # If true, sectionauthor and moduleauthor directives will be shown in the 83 | # output. They are ignored by default. 84 | #show_authors = False 85 | 86 | # The name of the Pygments (syntax highlighting) style to use. 87 | pygments_style = 'sphinx' 88 | 89 | # A list of ignored prefixes for module index sorting. 90 | #modindex_common_prefix = [] 91 | 92 | 93 | # -- Options for HTML output --------------------------------------------------- 94 | 95 | # The theme to use for HTML and HTML Help pages. Major themes that come with 96 | # Sphinx are currently 'default' and 'sphinxdoc'. 97 | html_theme = 'default' 98 | 99 | # Theme options are theme-specific and customize the look and feel of a theme 100 | # further. For a list of options available for each theme, see the 101 | # documentation. 102 | #html_theme_options = {} 103 | 104 | # Add any paths that contain custom themes here, relative to this directory. 105 | #html_theme_path = [] 106 | 107 | # The name for this set of Sphinx documents. If None, it defaults to 108 | # " v documentation". 109 | #html_title = None 110 | 111 | # A shorter title for the navigation bar. Default is the same as html_title. 112 | #html_short_title = None 113 | 114 | # The name of an image file (relative to this directory) to place at the top 115 | # of the sidebar. 116 | #html_logo = None 117 | 118 | # The name of an image file (within the static path) to use as favicon of the 119 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 120 | # pixels large. 121 | #html_favicon = None 122 | 123 | # Add any paths that contain custom static files (such as style sheets) here, 124 | # relative to this directory. They are copied after the builtin static files, 125 | # so a file named "default.css" will overwrite the builtin "default.css". 126 | html_static_path = ['_static'] 127 | 128 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 129 | # using the given strftime format. 130 | #html_last_updated_fmt = '%b %d, %Y' 131 | 132 | # If true, SmartyPants will be used to convert quotes and dashes to 133 | # typographically correct entities. 134 | #html_use_smartypants = True 135 | 136 | # Custom sidebar templates, maps document names to template names. 137 | # html_sidebars = { } 138 | 139 | # Additional templates that should be rendered to pages, maps page names to 140 | # template names. 141 | #html_additional_pages = {} 142 | 143 | # If false, no module index is generated. 144 | html_use_modindex = False 145 | 146 | # If false, no index is generated. 147 | html_use_index = False 148 | 149 | # If true, the index is split into individual pages for each letter. 150 | #html_split_index = False 151 | 152 | # If true, links to the reST sources are added to the pages. 153 | #html_show_sourcelink = True 154 | 155 | # If true, an OpenSearch description file will be output, and all pages will 156 | # contain a tag referring to it. The value of this option must be the 157 | # base URL from which the finished HTML is served. 158 | #html_use_opensearch = '' 159 | 160 | # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). 161 | #html_file_suffix = '' 162 | 163 | # Output file base name for HTML help builder. 164 | htmlhelp_basename = 'ScalaStyleGuidedoc' 165 | 166 | 167 | # -- Options for LaTeX output -------------------------------------------------- 168 | 169 | # The paper size ('letter' or 'a4'). 170 | #latex_paper_size = 'letter' 171 | 172 | # The font size ('10pt', '11pt' or '12pt'). 173 | #latex_font_size = '10pt' 174 | 175 | # Grouping the document tree into LaTeX files. List of tuples 176 | # (source start file, target name, title, author, documentclass [howto/manual]). 177 | latex_documents = [ 178 | ('index', 'ScalaStyleGuide.tex', u'Scala Style Guide Documentation', 179 | u'Scala Community', 'manual'), 180 | ] 181 | 182 | # The name of an image file (relative to this directory) to place at the top of 183 | # the title page. 184 | #latex_logo = None 185 | 186 | # For "manual" documents, if this is true, then toplevel headings are parts, 187 | # not chapters. 188 | #latex_use_parts = False 189 | 190 | # Additional stuff for the LaTeX preamble. 191 | #latex_preamble = '' 192 | 193 | # Documents to append as an appendix to all manuals. 194 | #latex_appendices = [] 195 | 196 | # If false, no module index is generated. 197 | #latex_use_modindex = True 198 | -------------------------------------------------------------------------------- /control_structures/comprehensions.rst: -------------------------------------------------------------------------------- 1 | .. Comprehensions 2 | 内包表記 3 | -------------- 4 | 5 | .. Scala has the ability to represent ``for``-comprehensions with more than one 6 | generator (usually, more than one ``<-`` symbol). In such cases, there are two 7 | alternative syntaxes which may be used:: 8 | Scalaは,1つ以上のジェネレータ(一般に,2つ以上の\ ``<-``\ 記号)を使った\ ``for``\ 内包表記を表現する事ができます。\ 9 | この場合,利用可能な2つの方法があります。 :: 10 | 11 | // 誤り! 12 | for (x <- board.rows; y <- board.files) 13 | yield (x, y) 14 | 15 | // 正しい! 16 | for { 17 | x <- board.rows 18 | y <- board.files 19 | } yield (x, y) 20 | 21 | .. While the latter style is more verbose, it is generally considered easier to read 22 | and more "scalable" (meaning that it does not become obfuscated as the complexity 23 | of the comprehension increases). You should prefer this form for all 24 | ``for``-comprehensions of more than one generator. Comprehensions with only a 25 | single generator (e.g. ``for (i <- 0 to 10) yield i``) should use the first 26 | form (parentheses rather than curly braces). 27 | 後者のスタイルはより冗長ですが,一般には読みやすく,より「スケーラブル」である(内包が複雑になってわかりにくくなる事が無い,\ 28 | という意味で)と言えます。2つ以上のジェネレータを含む\ ``for``\ 内包表記は,全てこのフォームで書くべきです。ジェネレータを\ 29 | 1つだけ持つ内包表記(e.g. ``for(i <- 0 to 10) yield i``\ )は,最初のフォーム(波括弧ではなく括弧)を用いるべきです。 30 | 31 | .. The exceptions to this rule are ``for``-comprehensions which lack a ``yield`` 32 | clause. In such cases, the construct is actually a loop rather than a functional 33 | comprehension and it is usually more readable to string the generators together 34 | between parentheses rather than using the syntactically-confusing ``} {`` 35 | construct:: 36 | このルールに対する例外は,\ ``yield``\ 節の無い\ ``for``\ 内包表記です。この場合, :: 37 | 38 | // 誤り! 39 | for { 40 | x <- board.rows 41 | y <- board.files 42 | } { 43 | printf("(%d, %d)", x, y) 44 | } 45 | 46 | // 正しい! 47 | for (x <- board.rows; y <- board.files) { 48 | printf("(%d, %d)", x, y) 49 | } 50 | 51 | .. Finally, ``for`` comprehensions are preferred to chained calls to 52 | ``map``, ``flatMap``, and ``filter``, as this can get difficult 53 | to read (this is one of the purposes of the enhanced ``for`` comprehension). 54 | 結果として,\ ``for``\ 内包表記はその可読性の高さ(これは\ ``for``\ 内包表記を拡張した理由の1つです)から\ 55 | \ ``map``\ ,\ ``flatMap``\ ,そして\ ``filter``\ の連鎖呼び出しよりも好ましいと言えます。 56 | -------------------------------------------------------------------------------- /control_structures/curly_braces.rst: -------------------------------------------------------------------------------- 1 | .. Curly-Braces 2 | 波括弧 3 | ------------ 4 | 5 | .. Curly-braces should be omitted in cases where the control structure represents 6 | a pure-functional operation and all branches of the control structure (relevant 7 | to ``if``/``else``) are single-line expressions. Remember the following guidelines: 8 | 制御構造が純粋関数的な操作を表現する場合や,制御の分岐が1行で書き表される場合には,波括弧は使わない\ 9 | 方がいいでしょう。次の指針を覚えておいてください。 10 | 11 | .. * ``if`` - Omit braces if you have an ``else`` clause. Otherwise, surround the 12 | contents with curly braces even if the contents are only a single line. 13 | * ``if`` - ``else``\ 節がある場合,波括弧はさけてください。\ ``else``\ 節がない場合は, 14 | 節の内容が1行であっても波括弧で括ってください。 15 | .. * ``while`` - Never omit braces (``while`` cannot be used in a pure-functional manner). 16 | * ``while`` - 必ず波括弧で括ってください(\ ``while``\ は純粋関数の流儀では使えません)。 17 | .. * ``for`` - Omit braces if you have a ``yield`` clause. Otherwise, surround the 18 | contents with curly-braces, even if the contents are only a single line. 19 | * ``for`` - ``yield``\ 節がある場合は,波括弧は使いません。無い場合は,節の内容が1行であっても波括弧で括ってください。 20 | .. * ``case`` - Omit braces if the ``case`` expression fits on a single line. Otherwise, 21 | use curly braces for clarity (even though they are not *required* by the parser). 22 | * ``case`` - ``case``\ 式が1行に収まる場合は,波括弧を使いません。1行に収まらなければ,\ 23 | 表現明快にするため,波括弧を使います(パーサが要求する訳ではありませんが)。 24 | 25 | :: 26 | 27 | val news = if (foo) 28 | goodNews() 29 | else 30 | badNews() 31 | 32 | if (foo) { 33 | println("foo was true") 34 | } 35 | 36 | news match { 37 | case "good" => println("Good news!") 38 | case "bad" => println("Bad news!") 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /control_structures/index.rst: -------------------------------------------------------------------------------- 1 | .. Control Structure 2 | 制御構造 3 | ================== 4 | 5 | .. All control structures should be written with a space following the defining 6 | keyword:: 7 | 全ての制御構造は,キーワードの後ろにスペースを置いて書くべきです。 :: 8 | 9 | // 正しい! 10 | if (foo) bar else baz 11 | for (i <- 0 to 10) { ... } 12 | while (true) { println("Hello, World!") } 13 | 14 | // 誤り! 15 | if(foo) bar else baz 16 | for(i <- 0 to 10) { ... } 17 | while(true) { println("Hello, World!") } 18 | 19 | .. toctree:: 20 | 21 | curly_braces 22 | comprehensions 23 | trivial_conditionals 24 | -------------------------------------------------------------------------------- /control_structures/trivial_conditionals.rst: -------------------------------------------------------------------------------- 1 | .. Trivial Conditionals 2 | ささいな条件文 3 | -------------------- 4 | 5 | .. There are certain situations where it is useful to create a short ``if``/``else`` 6 | expression for nested use within a larger expression. In Java, this sort of 7 | case would traditionally be handled by the ternary operator (``?``/``:``), a 8 | syntactic device which Scala lacks. In these situations (and really any time 9 | you have a extremely brief ``if``/``else`` expression) it is permissible to place 10 | the "then" and "else" branches on the same line as the ``if`` and ``else`` 11 | keywords:: 12 | 比較的大きな式の中で,ネストした短い\ ``if``/``else``\ 式が使えると便利な事があります。\ 13 | Javaだったら,伝統的に3項演算子(\ ``?``/``:``\ )を使うところですが,Scalaはこの構文を持ち合わせていません。\ 14 | こういう状況では(または極めて簡素な\ ``if``/``else``\ 式を持つ場合はどこでも),\ 15 | "then"と"else"の分岐を\ ``if``/``else``\ キーワードと同じ行に書くことが許されます。 :: 16 | 17 | val res = if (foo) bar else baz 18 | 19 | .. The key here is that readability is not hindered by moving both branches inline 20 | with the ``if``/``else``. Note that this style should never be used with 21 | imperative ``if`` expressions nor should curly braces be employed. 22 | ここで重要な事は,各分岐を\ ``if``/``else``\ とインラインにしても可読性は損なわれないという事です。\ 23 | この記法は,命令的な(関数的ではない)\ ``if``\ 式では決して使ってはならず,また波括弧を伴うべきではない\ 24 | ことに注意してください。 25 | 26 | -------------------------------------------------------------------------------- /declarations/fields.rst: -------------------------------------------------------------------------------- 1 | .. Fields 2 | フィールド 3 | ~~~~~~ 4 | 5 | .. Fields should follow the declaration rules for methods, taking special note of 6 | access modifier ordering and annotation conventions. 7 | フィールドはメソッド宣言のルールに従いますが,アクセス修飾子の順序とアノテーションの規約については注意が必要です。 8 | 9 | .. Lazy vals should use the ``lazy`` keyword directly before the ``val``:: 10 | 遅延評価valは\ ``lazy``\ キーワードを\ ``val``\ の直前に置くべきです。 :: 11 | 12 | private lazy val foo = bar() 13 | -------------------------------------------------------------------------------- /declarations/function_values/multi_expression_functions.rst: -------------------------------------------------------------------------------- 1 | .. Multi-Expression Functions 2 | 複数の式を持つ関数 3 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | .. Most function values are less trivial than the examples given above. Many contain 6 | more than one expression. In such cases, it is often more readable to split the 7 | function value across multiple lines. When this happens, only style (1) should 8 | be used. Style (4) becomes extremely difficult to follow when enclosed in large 9 | amounts of code. The declaration itself should loosely follow the declaration 10 | style for methods, with the opening brace on the same line as the assignment or 11 | invocation, while the closing brace is on its own line immediately following the 12 | last line of the function. Parameters should be on the same line as the opening 13 | brace, as should the "arrow" (``=>``):: 14 | 殆どの関数値はこれまでに見てきたものよりも複雑になり,多くが複数の式を持ったものになるでしょう。\ 15 | このような複雑な関数値は,行を分割すると読みやすくなることが多いです。\ 16 | 複数行に分割した場合には,1.のスタイルを適用します。4.のスタイルは,大きなコードの中では極端に\ 17 | 読み辛くなってしまうためです。宣言そのものはメソッドの宣言スタイルにほぼ従い,左波括弧は代入または呼び出し\ 18 | と同じ行に置き,右波括弧は関数の最後の行のすぐ次の行に書きます。\ 19 | パラメータと矢印(\ ``=>``\ )は左波括弧と同じ行に置きます。 :: 20 | 21 | val f1 = { (a: Int, b: Int) => 22 | a + b 23 | } 24 | 25 | .. As noted earlier, function values should leverage type inference whenever 26 | possible. 27 | 前に書いた通り,関数値は型推論を使えるところではどこでも最大限に活用するべきです。 28 | 29 | -------------------------------------------------------------------------------- /declarations/function_values/spacing.rst: -------------------------------------------------------------------------------- 1 | .. Spacing 2 | スペース 3 | ~~~~~~~ 4 | 5 | .. You will notice that both (1) and (4) insert spaces after the opening brace and 6 | before the closing brace. This extra spacing provides a bit of "breathing room" 7 | for the contents of the function and makes it easier to distinguish from the 8 | surrounding code. There are *no* cases when this spacing should be omitted. 9 | 1.と4.のスタイルは両方,左波括弧の後ろと右波括弧の前にスペースが挿入されている事に気が付いたと思います。\ 10 | この余分なスペースは,ちょっとした「休憩場所」です。これがあることによって,周囲のコードから関数定義を区別しやすくなります。\ 11 | このスペースは決して省略しては\ **いけません**\ 。 12 | 13 | -------------------------------------------------------------------------------- /declarations/index.rst: -------------------------------------------------------------------------------- 1 | .. Declarations 2 | 宣言 3 | ============ 4 | 5 | .. Classes 6 | クラス 7 | ------- 8 | 9 | .. Class/Object/Trait constructors should be declared all on one line, unless 10 | the line becomes "too long" (about 100 characters). In that case, put each 11 | constructor argument on its own line, indented **four** spaces:: 12 | クラス・オブジェクト・トレイトのコンストラクタは,行が「長すぎ」なければ(およそ100文字程度),1行で宣言するべきです。\ 13 | 行が長くなってしまう場合には,各コンストラクタ引数を行毎に配置して,スペース\ **4つ**\ でインデントします。 :: 14 | 15 | class Person(name: String, age: Int) { 16 | } 17 | 18 | class Person( 19 | name: String, 20 | age: Int, 21 | birthdate: Date, 22 | astrologicalSign: String, 23 | shoeSize: Int, 24 | favoriteColor: java.awt.Color) { 25 | def firstMethod = ... 26 | } 27 | 28 | .. If a class/object/trait extends anything, the same general rule applies, put 29 | it one one line unless it goes over about 100 characters, and then indent **four** 30 | spaces with each item being on its own line and **two** spaces for 31 | extensions; this provides visual separation between constructor arguments and extensions.:: 32 | クラス・オブジェクト・トレイトが何らか継承をしている場合,同様の規則があてはまります。100文字を越えなければ1行で宣言し,\ 33 | 越える場合にはスペース\ **4つ**\ で各引数をインデントし,継承している対象をスペース\ **2つ**\ でインデントします。\ 34 | こうするとコンストラクタ引数と継承の違いが見た目で区別がつきます。 :: 35 | 36 | class Person( 37 | name: String, 38 | age: Int, 39 | birthdate: Date, 40 | astrologicalSign: String, 41 | shoeSize: Int, 42 | favoriteColor: java.awt.Color) 43 | extends Entity 44 | with Logging 45 | with Identifiable 46 | with Serializable { 47 | } 48 | 49 | 50 | .. toctree:: 51 | 52 | ordering 53 | methods 54 | fields 55 | 56 | 57 | .. Function Values 58 | 関数値 59 | --------------- 60 | 61 | .. Scala provides a number of different syntactic options for declaring function 62 | values. For example, the following declarations are exactly equivalent: 63 | 関数値を宣言するための様々なオプションをScalaは提供しています。例えば,次の宣言は全く同じものです。 :: 64 | 65 | 1. ``val f1 = { (a: Int, b: Int) => a + b }`` 66 | 2. ``val f2 = (a: Int, b: Int) => a + b`` 67 | 3. ``val f3 = (_: Int) + (_: Int)`` 68 | 4. ``val f4: (Int, Int) => Int = { _ + _ }`` 69 | 70 | .. Of these styles, (1) and (4) are to be preferred at all times. (2) appears shorter 71 | in this example, but whenever the function value spans multiple lines (as is 72 | normally the case), this syntax becomes extremely unwieldy. Similarly, (3) is 73 | concise, but obtuse. It is difficult for the untrained eye to decipher the fact 74 | that this is even producing a function value. 75 | この内,1.と4.を常に使うべきです。2.はこの例では短く簡潔に見えますが,複数行にわたる場合(よく起こる)には非常に\ 76 | 判り辛くなります。同様に,3.も簡潔に書けますが,見慣れない人にとっては関数値を作っているということが判読し難いです。 77 | 78 | .. When styles (1) and (4) are used exclusively, it becomes very easy to distinguish 79 | places in the source code where function values are used. Both styles make use 80 | of curly braces (``{}``), allowing those characters to be a visual cue that a 81 | function value may be involved at some level. 82 | 1.と4.のスタイルだけを使えば,関数値が使われている場所を特定するのが極めて容易になります。どちらのスタイルにおいても\ 83 | 波括弧(\ ``{}``\ )を活用して,関数値がある事に気が付くための視覚的な手がかりとなります。 84 | 85 | .. toctree:: 86 | 87 | function_values/spacing 88 | function_values/multi_expression_functions 89 | -------------------------------------------------------------------------------- /declarations/methods.rst: -------------------------------------------------------------------------------- 1 | .. Methods 2 | メソッド 3 | ~~~~~~~ 4 | 5 | .. Methods should be declared according to the following pattern:: 6 | メソッドは次のパターンに従って宣言するべきです。 :: 7 | 8 | def foo(bar: Baz): Bin = expr 9 | 10 | .. The only exceptions to this rule are methods which return ``Unit``. Such methods 11 | should use Scala's syntactic sugar to avoid accidentally confusing return types:: 12 | ただし,\ ``Unit``\ 型を返すメソッドはこのルールへの反例となります。混乱を防ぐため,シンタックスシュガーを用いて\ 13 | 次の様に書くべきです。 :: 14 | 15 | def foo(bar: Baz) { // 戻り値の型はUnit 16 | expr 17 | } 18 | 19 | .. toctree:: 20 | 21 | methods/modifiers 22 | methods/currying 23 | methods/higher_order_functions 24 | -------------------------------------------------------------------------------- /declarations/methods/currying.rst: -------------------------------------------------------------------------------- 1 | .. Multiple Parameter Lists 2 | 複数のパラメータリスト 3 | ~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | .. In general, you should only use multiple parameter lists if there is a good reason to do so. 6 | These methods (or similarly declared functions) have a more verbose declaration and invocation syntax and are 7 | harder for less-experienced Scala developers to understand. 8 | 一般に,そうする理由があるときにだけ複数のパラメータリストを使うべきです。複数のパラメータリストを持つメソッドや関数は,\ 9 | 宣言も呼び出し側のコードも冗長になり,経験の少ない開発者にとっては判り辛くなります。 10 | 11 | .. There are three main reasons you should do this: 12 | 複数のパラメータリストを使うべき主な理由が3つあります。 13 | 14 | .. #. For a fluent API 15 | #. 流れるようなインターフェース 16 | 17 | .. Multiple parameter lists allow you to create your own "control structures":: 18 | 複数のパラメータリストを使えば,自前の「制御構造」を作ることができます。 :: 19 | 20 | def unless(exp:Boolean)(code: => Unit) = if (!exp) code 21 | unless(x < 5) { 22 | println("x was not less than five") 23 | } 24 | 25 | .. #. Implicit Parameters 26 | #. 暗黙のパラメータ 27 | 28 | .. When using implicit parameters, and you use the ``implicit`` keyword, it applies to the entire parameter list. 29 | Thus, if you want only some parameters to be impicit, you must use multiple parameter lists. 30 | ``implicit``\ キーワードを使って暗黙のパラメータを使っているとき,全てのパラメータリストにその効果が適用されます。\ 31 | このため,あるパラメータだけをimplicitにしたい場合は複数のパラメータリストを使用する必要があります。 32 | 33 | .. #. For type inference 34 | #. 型推論のため 35 | 36 | .. When invoking a method using only some of the parameter lists, the type inferencer can 37 | allow a simpler syntax when invoking the remaining parameter lists. Consider fold:: 38 | パラメータリストの一部だけ使ってメソッドを呼び出す時,型推論によって残りのパラメータリストをシンプルにすることができます。\ 39 | foldを例に考えてみましょう。 :: 40 | 41 | def foldLeft[B](z:B)(op: (A,B) => B):B 42 | List("").foldLeft(0)(_ + _.length) 43 | 44 | // 代わりにこうすると, 45 | def foldLeft[B](z: B, op: (B, A) => B): B 46 | // 上記の呼び出しはうまくいかず,型を明記しないといけない 47 | List("").foldLeft(0, (b: Int, a: String) => a + b.length) 48 | List("").foldLeft[Int](0, _ + _.length) 49 | 50 | .. For complex DSLs, or with type-names that are long, it can be difficult to fit the entire signature on one line. In those cases, 51 | alight the open-paren of the parameter lists, one list per line (i.e. if you can't put them all on one line, put one each per 52 | line):: 53 | 複雑なDSLや長い型名を扱うとき,宣言を1行に収めるのが難しくなります。こういう場合には,パラメータリストを1行毎に\ 54 | 揃えます(i.e. 1行に収められないときは,1行に1つずつ配置します)。 :: 55 | 56 | 57 | protected def forResource(resourceInfo:Any) 58 | (f: (JsonNode) => Any) 59 | (implicit urlCreator: URLCreator, configurer: OAuthConfiguration) = { 60 | 61 | 62 | -------------------------------------------------------------------------------- /declarations/methods/higher_order_functions.rst: -------------------------------------------------------------------------------- 1 | .. Higher-Order Functions 2 | 高階関数 3 | ~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | .. It's worth keeping in mind when declaring higher-order functions the fact that 6 | Scala allows a somewhat nicer syntax for such functions at call-site when the 7 | function parameter is curried as the last argument. For example, this is the 8 | ``foldl`` function in SML:: 9 | 高階関数を宣言する際には,関数パラメータが最後にあってカリー化されるときに許される,\ 10 | 呼び出し側にとっては喜ばしい構文がある事を心に留めておくといいでしょう。\ 11 | 例えば,これはSMLの\ ``foldl``\ 関数です。 :: 12 | 13 | fun foldl (f: ('b * 'a) -> 'b) (init: 'b) (ls: 'a list) = ... 14 | 15 | .. In Scala, the preferred style is the exact inverse:: 16 | Scalaでは,この真逆が好ましいスタイルです。 :: 17 | 18 | def foldLeft[A, B](ls: List[A])(init: B)(f: (B, A) => B) = ... 19 | 20 | .. By placing the function parameter *last*, we have enabled invocation syntax like 21 | the following:: 22 | 関数パラメータを\ **最後**\ にすることで,呼び出し側の構文を次のようにできます。 :: 23 | 24 | foldLeft(List(1, 2, 3, 4))(0) { _ + _ } 25 | 26 | .. The function value in this invocation is not wrapped in parentheses; it is 27 | syntactically quite disconnected from the function itself (``foldLeft``). This 28 | style is preferred for its brevity and cleanliness. 29 | この呼び出しで,関数値は括弧で囲われておらず,それゆえ関数値が関数そのもの(\ ``foldLeft``\ )から分離しています。\ 30 | その簡潔さから,このスタイルは好ましいと言えます。 31 | 32 | -------------------------------------------------------------------------------- /declarations/methods/modifiers.rst: -------------------------------------------------------------------------------- 1 | .. Modifiers 2 | 修飾子 3 | ~~~~~~~~~ 4 | 5 | .. Method modifiers should be given in the following order (when each is applicable): 6 | メソッド修飾子は次の順序で与えるべきです(それぞれ適用可能な場合)。 7 | 8 | .. #. Annotations, *each on their own line* 9 | #. Override modifier (``override``) 10 | #. Access modifier (``protected``, ``private``) 11 | #. Final modifier (``final``) 12 | #. ``def`` 13 | #. アノテーション,\ **1行に1つずつ** 14 | #. オーバーライド修飾子(\ ``override``\ ) 15 | #. アクセス修飾子(\ ``protected``\ ,\ ``private``\ ) 16 | #. ファイナル修飾子(\ ``final``\ ) 17 | #. ``def`` 18 | 19 | :: 20 | 21 | @Transaction 22 | @throws(classOf[IOException]) 23 | override protected final def foo() { 24 | ... 25 | } 26 | 27 | .. Body 28 | メソッド本体 29 | ~~~~ 30 | 31 | .. When a method body comprises a single expression which is less than 30 (or so) 32 | characters, it should be given on a single line with the method:: 33 | メソッド本体が30文字(かそこいら)未満の単一の式で構成される場合は,メソッド宣言と共に1行で書き下すべきです。 :: 34 | 35 | def add(a: Int, b: Int) = a + b 36 | 37 | .. When the method body is a single expression *longer* than 30 (or so) characters 38 | but still shorter than 70 (or so) characters, it should be given on the following 39 | line, indented two spaces:: 40 | メソッド本体がそれ以上長く,70文字(かそこいら)未満であれば,スペース2つでインデントして次の行に記述します。 :: 41 | 42 | def sum(ls: List[String]) = 43 | (ls map { _.toInt }).foldLeft(0) { _ + _ } 44 | 45 | .. The distinction between these two cases is somewhat artificial. Generally 46 | speaking, you should choose whichever style is more readable on a case-by-case 47 | basis. For example, your method declaration may be very long, while the expression 48 | body may be quite short. In such a case, it may be more readable to put the 49 | expression on the next line rather than making the declaration line unreadably 50 | long. 51 | これら2つの場合分けは,幾分属人的なものです。概して言えば,ケースバイケースで可読性の高い方を選択するべきです。\ 52 | 例えば,メソッド宣言が非常に長い一方で本体はとても短かったとします。この場合,本体を次の行に持って行った方が\ 53 | 宣言をわかりやすくして,読みやすくなるかもしれません。 54 | 55 | .. When the body of a method cannot be concisely expressed in a single line or is 56 | of a non-functional nature (some mutable state, local or otherwise), the body 57 | must be enclosed in braces:: 58 | メソッド本体が1行では適切に表現する事が難しかったり,関数的な性質のものではない(ミュータブルな状態や,ローカルなものなど)場合,\ 59 | 本体はブレースで囲うべきです。 :: 60 | 61 | def sum(ls: List[String]) = { 62 | val ints = ls map { _.toInt } 63 | ints.foldLeft(0) { _ + _ } 64 | } 65 | 66 | .. Methods which contain a single ``match`` expression should be declared in the 67 | following way:: 68 | 単一の\ ``match``\ 式からなるメソッドは次のように宣言しましょう。 :: 69 | 70 | // 正しい! 71 | def sum(ls: List[Int]): Int = ls match { 72 | case hd :: tail => hd + sum(tail) 73 | case Nil => 0 74 | } 75 | 76 | .. *Not* like this:: 77 | こうでは\ **ありません**\ 。 :: 78 | 79 | // 誤り! 80 | def sum(ls: List[Int]): Int = { 81 | ls match { 82 | case hd :: tail => hd + sum(tail) 83 | case Nil => 0 84 | } 85 | } 86 | 87 | -------------------------------------------------------------------------------- /declarations/ordering.rst: -------------------------------------------------------------------------------- 1 | .. Ordering Of Class Elements 2 | クラス要素の順序 3 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | .. All class/object/trait members should be declared interleaved with newlines. 6 | The only exceptions to this rule are ``var`` and ``val``. These may be declared 7 | without the intervening newline, but only if none of the fields have scaladoc 8 | and if all of the fields have simple (max of 20-ish chars, one line) definitions:: 9 | クラス・オブジェクト・トレイトのメンバは全て,空行を挟んで宣言するべきです。\ 10 | \ ``var``\ と\ ``val``\ だけがこのルールに対する例外になります。これらの要素は,scaladocのあるフィールドが1つも無く,\ 11 | 全てのフィールドがシンプルな(最大で20文字程度で,1行のもの)定義で収まる場合を除いて,空行を挟まずに宣言します。 :: 12 | 13 | class Foo { 14 | val bar = 42 15 | val baz = "Daniel" 16 | 17 | def doSomething() { ... } 18 | 19 | def add(x: Int, y: Int) = x + y 20 | } 21 | 22 | .. Fields should *precede* methods in a scope. The only exception is if the ``val`` 23 | has a block definition (more than one expression) and performs operations which 24 | may be deemed "method-like" (e.g. computing the length of a ``List``). In such 25 | cases, the non-trivial ``val`` may be declared at a later point in the file as 26 | logical member ordering would dictate. This rule *only* applies to ``val`` and 27 | ``lazy val``! It becomes very difficult to track changing aliases if ``var`` 28 | declarations are strewn throughout class file. 29 | スコープの中で,フィールドはメソッドの\ **前に**\ あるべきです。その例外は,\ ``val``\ の定義がブロックに\ 30 | なっている(2つ以上の式を持っている)と,「メソッドのような」操作(e.g. \ ``List``\ の長さを操作する)を持つ場合です。\ 31 | そのような場合,\ ``val``\ は,ファイルの後ろの方の,論理的な順序が意味する通りに配置します。\ 32 | このルールは\ ``val``\ と\ ``lazy val``\ に\ **のみ**\ 適用されます!\ ``var``\ の定義がファイル中に散在すると,\ 33 | その変化を辿るのが極めて困難になります。 34 | 35 | -------------------------------------------------------------------------------- /files/index.rst: -------------------------------------------------------------------------------- 1 | .. Files 2 | ファイル 3 | ===== 4 | 5 | .. As a rule, files should contain a *single* logical compilation unit. By "logical" 6 | I mean a class, trait or object. One exception to this guideline is for classes 7 | or traits which have companion objects. Companion objects should be grouped 8 | with their corresponding class or trait in the same file. These files should 9 | be named according to the class, trait or object they contain:: 10 | 原則,1つのファイルには単一の論理的なコンパイル単位を含むべきです。\ 11 | 「論理的」な単位とは,クラス,トレイト,またはオブジェクトを意味します。\ 12 | 唯一の例外は,コンパニオンオブジェクトを持つクラスまたはトレイトです。\ 13 | コンパニオンオブジェクトは,対応するクラスまたはトレイトと同じファイルに含むべきです。\ 14 | ファイル名は,そのファイルに含まれるクラス,トレイト,またはオブジェクトに基づいて命名します。 :: 15 | 16 | package com.novell.coolness 17 | 18 | class Inbox { ... } 19 | 20 | // コンパニオンオブジェクト 21 | object Inbox { ... } 22 | 23 | .. These compilation units should be placed within a file named ``Inbox.scala`` 24 | within the ``com/novell/coolness`` directory. In short, the Java file naming 25 | and positioning conventions should be preferred, despite the fact that Scala 26 | allows for greater flexibility in this regard. 27 | このコンパイル単位は,\ ``com/novell/coolness``\ ディレクトリの\ ``Inbox.scala``\ というファイルに\ 28 | あるべきです。つまり,Scalaの柔軟な命名・配置規則にかかわらず,Javaにおけるファイルの命名規則と配置規則を\ 29 | 守るべきだということです。 30 | 31 | .. toctree:: 32 | 33 | multi_unit_files 34 | -------------------------------------------------------------------------------- /files/multi_unit_files.rst: -------------------------------------------------------------------------------- 1 | .. Multi-Unit Files 2 | 複数のコンパイル単位を含むファイル 3 | ---------------- 4 | 5 | .. Despite what was said above, there are some important situations which warrant the 6 | inclusion of multiple compilation units within a single file. One common example 7 | is that of a sealed trait and several sub-classes (often emulating the ADT 8 | language feature available in functional languages):: 9 | ,1つのファイルに複数のコンパイル単位を含めるべき重要なシチュエーションがあります。\ 10 | よくある例として,シールドトレイトとそのサブクラス(関数型言語で利用可能な代数的データ構造を模してよく使われます)\ 11 | があります。 :: 12 | 13 | sealed trait Option[+A] 14 | 15 | case class Some[A](a: A) extends Option[A] 16 | 17 | case object None extends Option[Nothing] 18 | 19 | .. Because of the nature of sealed superclasses (and traits), all subtypes *must* 20 | be included in the same file. Thus, such a situation definitely qualifies as 21 | an instance where the preference for single-unit files should be ignored. 22 | シールドクラス(またはトレイト)の性質から,そのサブクラスは総じて同じファイルで定義\ **されなければなりません**\ 。\ 23 | したがって,こういった状況ではコンパイル単位をファイルの単位にするという嗜好は無視されます。 24 | 25 | .. Another case is when multiple classes logically form a single, cohesive group, 26 | sharing concepts to the point where maintenance is greatly served by containing 27 | them within a single file. These situations are harder to predict than the 28 | aforementioned sealed supertype exception. Generally speaking, if it is *easier* 29 | to perform long-term maintenance and development on several units in a single 30 | file rather than spread across multiple, then such an organizational strategy 31 | should be preferred for these classes. However, keep in mind that when multiple 32 | units are contained within a single file, it is often more difficult to find 33 | specific units when it comes time to make changes. 34 | また別のケースとして,複数のクラスが概念を共有して,1つの論理的なグループを形成しており,\ 35 | 同じファイルにまとまっていれば劇的に保守性が向上する場合があります。\ 36 | これは前述のシールドクラスの場合に比べて,予測し難いものです。\ 37 | 一般に,ファイルを分割するよりも同じファイルに含める方が長期の保守と開発が容易になる場合は,\ 38 | そうした方がいい結果になります。しかし,複数のコンパイル単位が同じファイルに含まれる場合,\ 39 | 変更を行おうとしたときに特定のコンパイル単位を見つけ出すのが難しくなると言うことも覚えておいてください。 40 | 41 | .. **All multi-unit files should be given camelCase names with a lower-case first letter.** 42 | This is a very important convention. It differentiates multi- from single-unit 43 | files, greatly easing the process of finding declarations. These filenames may 44 | be based upon a significant type which they contain (e.g. ``option.scala`` for 45 | the example above), or may be descriptive of the logical property shared by all 46 | units within (e.g. ``ast.scala``). 47 | **複数のコンパイル単位を含むファイル名は全て,小文字始まりのキャメルケースとするべきです。**\ 48 | これは非常に重要な規則です。こうすることによって,複数コンパイル単位を含むファイルを区別し,宣言を容易に探し出せる様になります。\ 49 | このファイル名は,その中にある特定のクラスに基づいて(e.g. 上記の例で言えば,\ ``option.scala``\ )命名しても,\ 50 | またその中にあるクラスが共有する論理的性質を説明するような名前(e.g. ``ast.scala``\ )にしても構いません。 51 | 52 | 53 | -------------------------------------------------------------------------------- /indentation/index.rst: -------------------------------------------------------------------------------- 1 | .. Indentation 2 | インデント 3 | =========== 4 | 5 | .. Indentation should follow the "2-space convention". Thus, instead of indenting 6 | like this:: 7 | インテントは「2スペース規約」に従うべきです。したがって,次の様にするのでは無く, :: 8 | 9 | // 誤り! 10 | class Foo { 11 | def bar = ... 12 | } 13 | 14 | .. You should indent like this:: 15 | 次の様にインデントするべきです。 :: 16 | 17 | // 正しい! 18 | class Foo { 19 | def bar = .. 20 | } 21 | 22 | .. The Scala language encourages a startling amount of nested scopes and logical 23 | blocks (function values and such). Do yourself a favor and don't penalize yourself 24 | syntactically for opening up a new block. Coming from Java, this style does take 25 | a bit of getting used to, but it is well worth the effort. 26 | Scalaではネストしたスコープと論理ブロックが驚くほど多用されます(関数値など)。積極的に新しいブロックを作ってください。\ 27 | Java出身の方にはこのスタイルにはあまりなじみがないかもしれませんが,非常に有用です。 28 | 29 | .. toctree:: 30 | 31 | line_wrapping 32 | methods_with_numerous_arguments 33 | -------------------------------------------------------------------------------- /indentation/line_wrapping.rst: -------------------------------------------------------------------------------- 1 | .. Line Wrapping 2 | 行の折り返し 3 | ------------- 4 | 5 | .. There are times when a single expression reaches a length where it becomes 6 | unreadable to keep it confined to a single line (usually that length is anywhere 7 | above 80 characters). In such cases, the *preferred* approach is to simply 8 | split the expression up into multiple expressions by assigning intermediate results 9 | to values or by using the `pipeline operator`_. However, this is not always a 10 | practical solution. 11 | 単一の式が読みづらい程に長くなってしまったら(大抵,80文字を越えるとそうなる),\ 12 | \ **好ましい**\ アプローチは,中間結果値を用意したり\ `パイプライン演算子`_\ \ 13 | を使ってその式を分割することです。しかし,この手法が必ずしも常に現実的な解決策となる訳ではありません。 14 | 15 | .. When it is absolutely necessary to wrap an expression across more than one line, 16 | each successive line should be indented two spaces from the *first*. Also 17 | remember that Scala requires each "wrap line" to either have an unclosed 18 | parenthetical or to end with an infix binary function or operator in which the 19 | right parameter is not given:: 20 | 式を2つ以上の行に分割する必要に迫られたら,続く行はスペース2つ分\ **最初の行**\ からインデントするべきです。\ 21 | また,Scalaは各「ラップされる行」に閉じていない括弧か,適切なパラメータが渡されていない中置の2項関数または演算子\ 22 | を要求する事も頭の片隅に留めておいてください。 :: 23 | 24 | val result = 1 + 2 + 3 + 4 + 5 + 6 + 25 | 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 26 | 15 + 16 + 17 + 18 + 19 + 20 27 | 28 | .. Without this trailing operator, Scala will infer a semi-colon at the end of a 29 | line which was intended to wrap, throwing off the compilation sometimes without 30 | even so much as a warning. 31 | この演算子が無いと,ラップするつもりの行末にScalaはセミコロンを想定してしまいます。\ 32 | その結果,わかりやすい警告の無いままコンパイルに失敗します。 33 | 34 | .. _パイプライン演算子: http://paste.pocoo.org/show/134013/ 35 | 36 | -------------------------------------------------------------------------------- /indentation/methods_with_numerous_arguments.rst: -------------------------------------------------------------------------------- 1 | .. Methods with Numerous Arguments 2 | 多数の引数をとるメソッド 3 | ------------------------------- 4 | 5 | .. When calling a method which takes numerous arguments (in the range of five or 6 | more), it is often necessary to wrap the method invocation onto multiple lines. 7 | In such cases, put all arguments on a line by themselves, indented two spaces 8 | from the current indent level:: 9 | 多数の引数(5つ以上の)をとるメソッドを呼び出す際,複数行に分割した方が良い場合がよくあります。\ 10 | このとき,現在のインデントレベルからスペース2つ分インデントして全ての引数を配置してください。 :: 11 | 12 | foo( 13 | someVeryLongFieldName, 14 | andAnotherVeryLongFieldName, 15 | "this is a string", 16 | 3.1415) 17 | 18 | .. This way, all parameters line up, but you don't need to re-align them if 19 | you change the name of the method later on. 20 | こうすると,メソッド名を後で変更した際に再度パラメータを整列する必要がありません。 21 | 22 | .. Great care should be taken to avoid these sorts of invocations well into the 23 | length of the line. More specifically, such an invocation should be avoided 24 | when each parameter would have to be indented more than 50 spaces to achieve 25 | alignment. In such cases, the invocation itself should be moved to the next 26 | line and indented two spaces:: 27 | この類の呼び出しを避けるため,行の長さにも大いに気を配る必要があります。より具体的に言えば,各パラメータを整えるのに\ 28 | 50あまりものスペースが必要となる場合にはこのような呼び出しは避けるべきです。この場合,呼び出しそのものを次の行に移動して\ 29 | 2スペース分インデントすると良いでしょう。 :: 30 | 31 | // 正しい! 32 | val myOnerousAndLongFieldNameWithNoRealPoint = 33 | foo( 34 | someVeryLongFieldName, 35 | andAnotherVeryLongFieldName, 36 | "this is a string", 37 | 3.1415) 38 | 39 | // 誤り! 40 | val myOnerousAndLongFieldNameWithNoRealPoint = foo(someVeryLongFieldName, 41 | andAnotherVeryLongFieldName, 42 | "this is a string", 43 | 3.1415) 44 | 45 | .. Better yet, just try to avoid any method which takes more than two or three 46 | parameters! 47 | 更に,3,4個以上の引数をとるメソッドを使わないようにすれば言うことはありません! 48 | 49 | -------------------------------------------------------------------------------- /index.rst: -------------------------------------------------------------------------------- 1 | Scalaスタイルガイド 2 | ================= 3 | 4 | EPFLの提供する公式スタイルガイドや,Artimaのようなコミュニティサイトによる非公式ガイドの代わりに,殆どの場合に従うべき\ 5 | Scalaのスタイルにおけるガイドラインの概略を示す事を意図してこの文書は作られました。\ 6 | このガイドでは,\ **なぜ**\ そのスタイルが推奨されるのか,またその代替案がどのようにしてそのスタイルに関連するのかを,\ 7 | できる限り多くの箇所で詳細に記述するよう努めています。\ 8 | 他の全てのスタイルガイドと同様に,この文書もいずれ破られるルールの一覧として扱ってください。\ 9 | ここで提示するスタイルよりも好ましい別のスタイルがきっと現れるはずです。\ 10 | 11 | .. In lieu of an official style guide from EPFL, or even an unofficial guide from 12 | a community site like Artima, this document is intended to outline some basic 13 | Scala stylistic guidelines which should be followed with more or less fervency. 14 | Wherever possible, this guide attempts to detail *why* a particular style is 15 | encouraged and how it relates to other alternatives. As with all style guides, 16 | treat this document as a list of rules to be broken. There are certainly times 17 | when alternative styles should be preferred over the ones given here. 18 | 19 | コンテンツ: 20 | 21 | .. toctree:: 22 | :maxdepth: 3 23 | 24 | overview 25 | 26 | indentation/index 27 | naming_conventions/index 28 | types/index 29 | nested_blocks/index 30 | declarations/index 31 | control_structures/index 32 | method_invocation/index 33 | files/index 34 | scaladoc/index 35 | changelog 36 | 37 | Indices and tables 38 | ================== 39 | 40 | * :ref:`genindex` 41 | * :ref:`search` 42 | 43 | -------------------------------------------------------------------------------- /make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | set SPHINXBUILD=sphinx-build 6 | set BUILDDIR=_build 7 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 8 | if NOT "%PAPER%" == "" ( 9 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 10 | ) 11 | 12 | if "%1" == "" goto help 13 | 14 | if "%1" == "help" ( 15 | :help 16 | echo.Please use `make ^` where ^ is one of 17 | echo. html to make standalone HTML files 18 | echo. dirhtml to make HTML files named index.html in directories 19 | echo. pickle to make pickle files 20 | echo. json to make JSON files 21 | echo. htmlhelp to make HTML files and a HTML help project 22 | echo. qthelp to make HTML files and a qthelp project 23 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 24 | echo. changes to make an overview over all changed/added/deprecated items 25 | echo. linkcheck to check all external links for integrity 26 | echo. doctest to run all doctests embedded in the documentation if enabled 27 | goto end 28 | ) 29 | 30 | if "%1" == "clean" ( 31 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 32 | del /q /s %BUILDDIR%\* 33 | goto end 34 | ) 35 | 36 | if "%1" == "html" ( 37 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 38 | echo. 39 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 40 | goto end 41 | ) 42 | 43 | if "%1" == "dirhtml" ( 44 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 45 | echo. 46 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 47 | goto end 48 | ) 49 | 50 | if "%1" == "pickle" ( 51 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 52 | echo. 53 | echo.Build finished; now you can process the pickle files. 54 | goto end 55 | ) 56 | 57 | if "%1" == "json" ( 58 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 59 | echo. 60 | echo.Build finished; now you can process the JSON files. 61 | goto end 62 | ) 63 | 64 | if "%1" == "htmlhelp" ( 65 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 66 | echo. 67 | echo.Build finished; now you can run HTML Help Workshop with the ^ 68 | .hhp project file in %BUILDDIR%/htmlhelp. 69 | goto end 70 | ) 71 | 72 | if "%1" == "qthelp" ( 73 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 74 | echo. 75 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 76 | .qhcp project file in %BUILDDIR%/qthelp, like this: 77 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ScalaStyleGuide.qhcp 78 | echo.To view the help file: 79 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ScalaStyleGuide.ghc 80 | goto end 81 | ) 82 | 83 | if "%1" == "latex" ( 84 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 85 | echo. 86 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 87 | goto end 88 | ) 89 | 90 | if "%1" == "changes" ( 91 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 92 | echo. 93 | echo.The overview file is in %BUILDDIR%/changes. 94 | goto end 95 | ) 96 | 97 | if "%1" == "linkcheck" ( 98 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 99 | echo. 100 | echo.Link check complete; look for any errors in the above output ^ 101 | or in %BUILDDIR%/linkcheck/output.txt. 102 | goto end 103 | ) 104 | 105 | if "%1" == "doctest" ( 106 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 107 | echo. 108 | echo.Testing of doctests in the sources finished, look at the ^ 109 | results in %BUILDDIR%/doctest/output.txt. 110 | goto end 111 | ) 112 | 113 | :end 114 | -------------------------------------------------------------------------------- /method_invocation/arity0/index.rst: -------------------------------------------------------------------------------- 1 | .. Arity-0 2 | 引数のないメソッド 3 | ------- 4 | 5 | .. Scala allows the omission of parentheses on methods of arity-0 (no arguments):: 6 | Scalaでは,引数のないメソッドの呼び出しにおいて括弧を省略することができます。 :: 7 | 8 | reply() 9 | 10 | // は次と等しい 11 | 12 | reply 13 | 14 | .. However, this syntax should *only* be used when the method in question has no 15 | side-effects (purely-functional). In other words, it would be acceptable to 16 | omit parentheses when calling ``queue.size``, but not when calling ``println()``. 17 | This convention mirrors the method declaration convention given above. 18 | しかし,この構文は,そのメソッドが副作用の無い(純粋関数的な)場合に\ **のみ**\ 使うべきです。\ 19 | つまり,\ ``queue.size``\ を呼び出す時には括弧を省略できるが,\ ``println()``\ ではできないということです。\ 20 | この慣習は,上述のメソッド宣言における規約と対をなします。 21 | 22 | .. Religiously observing this convention will *dramatically* improve code readability 23 | and will make it much easier to understand at a glance the most basic operation 24 | of any given method. Resist the urge to omit parentheses simply to save two 25 | characters! 26 | この規約を忠実に守ることによって,コードの可読性は\ **劇的に**\ 向上し,\ 27 | 単に2文字書く労力を節約するために括弧を省略したくなる衝動を抑えて下さい! 28 | 29 | .. toctree:: 30 | 31 | suffix_notation 32 | -------------------------------------------------------------------------------- /method_invocation/arity0/suffix_notation.rst: -------------------------------------------------------------------------------- 1 | .. Suffix Notation 2 | 後置記法 3 | ~~~~~~~~~~~~~~~ 4 | 5 | .. Scala allows methods of arity-0 to be invoked using suffix notation:: 6 | Scalaでは,arity-0のメソッドは後置記法で呼び出す事が可能です。 :: 7 | 8 | names.toList 9 | 10 | // は次と同様 11 | 12 | names toList 13 | 14 | .. This style should be used with great care. In order to avoid ambiguity in Scala's 15 | grammar, any method which is invoked via suffix notation must be the *last* item 16 | on a given line. Also, the following line must be completely empty, otherwise 17 | Scala's parser will assume that the suffix notation is actually infix and will 18 | (incorrectly) attempt to incorporate the contents of the following line into the 19 | suffix invocation:: 20 | この記法の使用には十分注意が必要です。構文解析の曖昧さを回避するため,後置記法で呼び出されるメソッドは,\ 21 | \ **必ず**\ 行の最後に位置しなければなりません。また,後続の行は空行でなくてはならず,さもなければ\ 22 | Scalaのパーサはそのメソッドを(誤って)中値記法とみなし,後続の行をまとめて解析しようとします。 :: 23 | 24 | names toList 25 | val answer = 42 // コンパイルできない! 26 | 27 | .. This style should only be used on methods with no side-effects, preferably ones 28 | which were declared without parentheses (see above). The most common acceptable 29 | case for this syntax is as the last operation in a chain of infix method calls:: 30 | メソッドの後置記法は,副作用の無い,なるべくなら(上述の)括弧なしで宣言されたメソッドに対して使用するべきです。\ 31 | この記法の最もよく見られるケースは,中値記法のメソッドチェインの最後の操作としての用法です。 :: 32 | 33 | // 慣用的かつ許容し得る用法 34 | names map { _.toUpperCase } filter { _.length > 5 } toStream 35 | 36 | .. In this case, suffix notation must be used with the ``toStream`` function, 37 | otherwise a separate value assignment would have been required. However, under 38 | less specialized circumstances, suffix notation should be avoided:: 39 | この場合,\ ``toStream``\ 関数は後置記法で呼び出される必要があり,そうでなければ,分離した値の代入が必要になります。\ 40 | しかし,より一般的に言えば,後置記法は避けるべき場合の方が多いでしょう。 :: 41 | 42 | // 誤り! 43 | val ls = names toList 44 | 45 | // 正しい! 46 | val ls = names.toList 47 | 48 | .. The primary exception to this rule is for domain-specific languages. One very 49 | common use of suffix notation which goes against the above is converting a 50 | ``String`` value into a ``Regexp``:: 51 | このルールに対する最も主要な例外が,ドメイン特化言語です。上記のルールに反する,多々見受けられる用法の1つが\ ``String``\ 値\ 52 | の\ ``Regexp``\ への変換です。 :: 53 | 54 | // 許容し得る用法 55 | val reg = """\d+(\.\d+)?"""r 56 | 57 | .. In this example, ``r`` is actually a method available on type ``String`` via an 58 | implicit conversion. It is being called in suffix notation for brevity. 59 | However, the following would have been just as acceptable:: 60 | この例で,\ ``r``\ は暗黙の変換を通じて\ ``String``\ 型で利用可能なメソッドであり,\ 61 | 簡潔さのために後置記法で呼び出されています。しかし,次の例の方がより好ましいでしょう。 :: 62 | 63 | // より安全な呼び出し方 64 | val reg = """\d+(\.\d+)?""".r 65 | 66 | -------------------------------------------------------------------------------- /method_invocation/arity1/higher_order_functions.rst: -------------------------------------------------------------------------------- 1 | .. Higher-Order Functions 2 | 高階関数 3 | ~~~~~~~~~~~~~~~~~~~~~~ 4 | 5 | .. As noted, methods which take functions as parameters (such as ``map`` or ``foreach``) 6 | should be invoked using infix notation. It is also *possible* to invoke such 7 | methods in the following way:: 8 | 前述の通り,関数をパラメータとして取るメソッド(\ ``map``\ や\ ``foreach``\ の様な)は中値記法で呼び出す\ 9 | べきですが,次の様に呼び出すことも\ **可能**\ ではあります。 :: 10 | 11 | names.map { _.toUpperCase } // 誤り! 12 | 13 | .. This style is *not* the accepted standard! The reason to avoid this style is 14 | for situations where more than one invocation must be chained together:: 15 | この呼び出し方は標準としては到底受け入れられ\ **ません**\ !というのも,メソッドチェインの場合に問題があるからです。 :: 16 | 17 | // 誤り! 18 | names.map { _.toUpperCase }.filter { _.length > 5 } 19 | 20 | // 正しい! 21 | names map { _.toUpperCase } filter { _.length > 5 } 22 | 23 | .. Both of these work, but the former exploits an extremely unintuitive wrinkle in 24 | Scala's grammar. The sub-expression ``{ _.toUpperCase }.filter`` when taken in 25 | isolation looks for all the world like we are invoking the ``filter`` method on 26 | a function value. However, we are actually invoking ``filter`` on the result of 27 | the ``map`` method, which takes the function value as a parameter. This syntax 28 | is confusing and often discouraged in Ruby, but it is shunned outright in Scala. 29 | これらは共に意図通りに動作しますが,前者は,極めて非直観的なScalaの文法の欠点を不当に利用したものです。\ 30 | 途中の\ ``{ _.toUpperCase }.filter``\ の部分を取り出して見ると,\ ``filter``\ メソッドを\ 31 | 関数値に対して呼び出している様に見えますが,実際には関数値をパラメータに取る\ ``map``\ メソッドの結果に対して\ 32 | \ ``filter``\ メソッドを呼び出しています。この構文はRubyではたびたび混乱の元になり,使用が推奨されていませんが,\ 33 | Scalaでは絶対に使いません。 34 | 35 | -------------------------------------------------------------------------------- /method_invocation/arity1/index.rst: -------------------------------------------------------------------------------- 1 | .. Arity-1 2 | 1引数のメソッド 3 | ------- 4 | 5 | .. Scala has a special syntax for invoking methods of arity-1 (one argument):: 6 | Scalaには1引数のメソッドを呼び出す特別な構文があります。 :: 7 | 8 | names.mkString(",") 9 | 10 | // は次と等しい 11 | 12 | names mkString "," 13 | 14 | .. This syntax is formally known as "infix notation". It should *only* be used for 15 | purely-functional methods (methods with no side-effects) - such as ``mkString`` - 16 | or methods which take functions as parameters - such as ``foreach``:: 17 | この構文は正式には「中値記法」として知られており,純粋関数的な(副作用の無い)メソッド - ``mkString``\ の様な - もしくは\ 18 | パラメータとして関数を取るメソッド - ``foreach``\ の様な - に\ **のみ**\ 使用されるべきです。 :: 19 | 20 | // 正しい! 21 | names foreach { n => println(n) } 22 | names mkString "," 23 | optStr getOrElse "" 24 | 25 | // 誤り! 26 | javaList add item 27 | 28 | .. toctree:: 29 | 30 | higher_order_functions 31 | -------------------------------------------------------------------------------- /method_invocation/index.rst: -------------------------------------------------------------------------------- 1 | .. Method Invocation 2 | メソッド呼び出し 3 | ================= 4 | 5 | .. Generally speaking, method invocation in Scala follows Java conventions. In 6 | other words, there should not be a space between the invocation target and the 7 | dot (``.``), nor a space between the dot and the method name, nor should there 8 | be any space between the method name and the argument-delimiters (parentheses). 9 | Each argument should be separated by a single space *following* the comma (``,``):: 10 | Scalaでは,メソッド呼び出しは一般にJavaの慣習に従います。言い方を変えれば,呼び出し先とドット(\ ``.``\ )の間\ 11 | ,ドットとメソッド名の間,そしてメソッド名と引数を囲う括弧の間にスペースを入れないということです。\ 12 | 各引数は,カンマ(\ ``,``\ )に\ **続く**\ スペース1つで区切られます。 :: 13 | 14 | foo(42, bar) 15 | target.foo(42, bar) 16 | target.foo() 17 | 18 | .. toctree:: 19 | 20 | arity0/index 21 | arity1/index 22 | operators 23 | -------------------------------------------------------------------------------- /method_invocation/operators.rst: -------------------------------------------------------------------------------- 1 | .. Operators 2 | 演算子 3 | --------- 4 | 5 | .. Symbolic methods (operators) should *always* be invoked using infix notation with 6 | spaces separated the target, the operator and the parameter:: 7 | 記号メソッド(演算子)は,\ **常に**\ 対象オブジェクト,演算子と引数をスペースで区切った中置記法で記述するべきです。 :: 8 | 9 | // 正しい! 10 | "daniel" + " " + "Spiewak" 11 | 12 | // 誤り! 13 | "daniel"+" "+"spiewak" 14 | 15 | .. For the most part, this idiom follows Java and Haskell syntactic conventions. 16 | 殆どの箇所で,このイディオムはJavaとHaskellの慣習に従います。 17 | 18 | .. Operators which take more than one parameter (they do exist!) should still be 19 | invoked using infix notation, delimited by spaces:: 20 | 2つ以上の引数をとる演算子(実際にあります)もまた,スペース区切りの中置記法で呼び出すべきです。 :: 21 | 22 | foo ** (bar, baz) 23 | 24 | .. Such operators are fairly rare, however, and should be avoided during API design. 25 | こういった演算子は極めて稀で,またAPIを設計する際には避けるべきです。 26 | 27 | .. Finally, the use of the ``/:`` and ``:\`` should be avoided in preference to the more explicit 28 | ``foldLeft`` and ``foldRight`` method of ``Iterator``. The right-associativity of the ``/:`` 29 | can lead to extremely confusing code, at the benefit of saving a few characters. 30 | 最後に,\ ``Iterator``\ のメソッド\ ``/:``\ と\ ``:\``\ の使用は避けて,より明示的な\ ``foldLeft``\ と\ 31 | \ ``foldRight``\ を使用するべきです。\ ``/:``\ の右結合は,数文字の節約に見合わず極めて可読性を下げる可能性があります。 32 | -------------------------------------------------------------------------------- /naming_conventions/annotations.rst: -------------------------------------------------------------------------------- 1 | .. Annotations 2 | アノテーション 3 | ----------- 4 | 5 | .. Annotations, such as ``@volatile`` should be in camel-case, with the first letter 6 | being lower case:: 7 | ``@volatile``\ のようなアノテーションは,最初の1文字を小文字にしたキャメルケースとするべきです。 :: 8 | 9 | class cloneable extends StaticAnnotation 10 | 11 | .. This convention is used throughout the Scala library, even though 12 | it is not consistent with Java annotations. 13 | この規約はJavaのアノテーションのそれとは異なりますが,Scalaの標準ライブラリ全体で守られています。 14 | 15 | -------------------------------------------------------------------------------- /naming_conventions/classes_traits.rst: -------------------------------------------------------------------------------- 1 | .. Classes/Traits 2 | クラス・トレイト 3 | -------------- 4 | 5 | .. Classes should be named in the camelCase style with the very first letter of the 6 | name capitalized:: 7 | クラス名は最初の文字を大文字にしたキャメルケースにします。 :: 8 | 9 | class MyFairLady 10 | 11 | .. This mimics the Java naming convention for classes. 12 | これはJavaにおけるクラスの命名規約と同じです。 13 | 14 | -------------------------------------------------------------------------------- /naming_conventions/fields.rst: -------------------------------------------------------------------------------- 1 | フィールド 2 | ------ 3 | 4 | .. Field names should be in camelCase with the first letter lower-case:: 5 | フィールド名は最初の1文字を小文字にしたキャメルケースにするべきです。 :: 6 | 7 | val myFairField = ... 8 | 9 | 10 | -------------------------------------------------------------------------------- /naming_conventions/index.rst: -------------------------------------------------------------------------------- 1 | .. Naming Conventions 2 | 命名規約 3 | ================== 4 | 5 | .. Generally speaking, Scala uses "camelCase" naming conventions. That is, each 6 | word (except possibly the first) is delimited by capitalizing its first letter. 7 | Underscores (``_``) are *heavily* discouraged as they have special meaning within 8 | the Scala syntax. Please note that there are a few important exceptions to this 9 | guideline (as given below). 10 | 一般に,Scalaは「キャメルケース」命名規約を用います。つまり,各単語(最初の単語は違うかもしれません)をその最初の文字を\ 11 | 大文字にすることで区切ります。アンダースコア(\ ``_``\ )はScalaの文法で特別な意味を持つため,\ 12 | 使わないように\ **厳しく**\ 自制してください。\ 13 | いくつかの重要な例外規則が,下に挙げたものの中にあることに留意してください。 14 | 15 | .. toctree:: 16 | 17 | classes_traits 18 | objects 19 | packages 20 | methods/index 21 | fields 22 | type_parameters/index 23 | type_aliases 24 | annotations 25 | special_note_on_brevity 26 | -------------------------------------------------------------------------------- /naming_conventions/methods/accessors_mutators.rst: -------------------------------------------------------------------------------- 1 | .. Accessors/Mutators 2 | アクセッサ・ミューテータ 3 | ~~~~~~~~~~~~~~~~~~ 4 | 5 | .. Scala does *not* follow the Java convention of prepending ``set``/``get`` to 6 | mutator and accessor methods (respectively). Instead, the following conventions 7 | are used: 8 | Scalaは,ミューテータ・アクセッサメソッドに\ ``set``/``get``\ を前置するJavaの慣習に従い\ **ません**\ 。\ 9 | 代わりに,以下の慣例があります。 10 | 11 | .. * For accessors of *most* boolean and non-boolean properties, the name of the 12 | method should be the name of the property 13 | * For accessors of *some* boolean properties, the name of the method may be the 14 | capitalized name of the property with "``is``" prepended (e.g. ``isEmpty``). 15 | This should only be the case when no corresponding mutator is provided. Please 16 | note that the Lift_ convention of appending "``_?``" to boolean accessors is 17 | non-standard and not used outside of the Lift framework. 18 | * For mutators, the name of the method should be the name of the property with 19 | "``_=``" appended. As long as a corresponding accessor with that particular 20 | property name is defined on the enclosing type, this convention will enable 21 | a call-site mutation syntax which mirrors assignment. 22 | * **殆どの**\ ブーリアン・非ブーリアンプロパティのアクセッサにおいて,プロパティ名と同じメソッド名とします。 23 | * **いくらかの**\ ブーリアンプロパティのアクセッサにおいて,プロパティ名の語頭を大文字にして\ ``is``\ を\ 24 | 前置したもの(e.g. ``isEmpty``\ )をメソッド名とすることもできます。\ 25 | ただし,これは対応するミューテータが無い場合にのみ適用すべきです。\ 26 | ブーリアンアクセッサにおける\ Lift_\ の"``_?``"を前置する慣習は,Liftフレームワーク以外では用いられて\ 27 | おらず,標準的なものでは無いと言うことに注意してください。 28 | * ミューテータメソッド名は,プロパティ名に"``_=``"を後置したものとするべきです。対応するアクセッサが上述した適切な\ 29 | ネーミングがされたものであれば,呼び出し側に対称性のある構文を提供できます。 30 | 31 | :: 32 | 33 | class Foo { 34 | 35 | def bar = ... 36 | 37 | def bar_=(bar: Bar) { 38 | ... 39 | } 40 | 41 | def isBaz = ... 42 | } 43 | 44 | val foo = new Foo 45 | foo.bar // アクセッサ 46 | foo.bar = bar2 // ミューテータ 47 | foo.isBaz // ブーリアンプロパティ 48 | 49 | .. Quite unfortunately, these conventions fall afoul of the Java convention to name 50 | the private fields encapsulated by accessors and mutators according to the 51 | property they represent. For example:: 52 | 極めて遺憾な事に,これらの慣習はJavaにおけるそれとアクセッサとミューテータでカプセル化されたプライベートフィールドの\ 53 | 命名において,その特質の違いから相反するものとなります。例えば,次のコードを見てください。 :: 54 | 55 | public class Company { 56 | private String name; 57 | 58 | public String getName() { 59 | return name; 60 | } 61 | 62 | public void setName(String name) { 63 | this.name = name; 64 | } 65 | } 66 | 67 | .. If we were to attempt to adopt this convention within Scala while observing the 68 | accessor naming conventions given above, the Scala compiler would complain about 69 | a naming collision between the ``name`` field and the ``name`` method. There are 70 | a number of ways to avoid this problem and the community has yet to standardize 71 | on any one of them. The following illustrates one of the less error-prone 72 | conventions:: 73 | アクセッサにおける上記の命名規則に従いながら,Scalaのこの規約を採用しようとしたとき,Scalaコンパイラは\ 74 | ``name``\ フィールドと\ ``name``\ メソッドの名前が衝突していると文句を言ってくるでしょう。\ 75 | この問題を回避する方法は多数あり,コミュニティではまだ標準化がなされていません。\ 76 | 次のコード例は,数多の回避方法から,エラーになり辛い規約の1つを示しています。 :: 77 | 78 | class Company { 79 | private val _name: String = _ 80 | 81 | def name = _name 82 | 83 | def name_=(name: String) { 84 | _name = name 85 | } 86 | } 87 | 88 | .. While Hungarian notation is terribly ugly, it does have the advantage of 89 | disambiguating the ``_name`` field without cluttering the identifier. The 90 | underscore is in the prefix position rather than the suffix to avoid any danger 91 | of mistakenly typing ``name _`` instead of ``name_``. With heavy use of Scala's 92 | type inference, such a mistake could potentially lead to a very confusing error. 93 | ハンガリアン記法は最低最悪に見苦しいものですが,識別子をぐちゃぐちゃにせずに\ ``_name``\ フィールド\ 94 | よりも明確にできるという利点はあります。\ ``name_``\ と打ちたかったのを\ ``name _``\ と間違えて打つ危険を避ける\ 95 | ため,アンダースコアは後置よりも前置の方が好ましいでしょう。Scalaの型推論を多用すると,このタイプミスが\ 96 | 極めて判り辛いエラーを招く可能性があります。 97 | 98 | .. Note that fields may actually be used in a number of situations where accessors 99 | and mutators would be required in languages like Java. Always prefer fields over 100 | methods when given the choice. 101 | Javaの様な,アクセッサ・ミューテータを必要とする言語でフィールドが利用される事が多々あると言うことを気に留めておいてください。\ 102 | 選択を迫られたら,常にフィールドをメソッドに優先してください。 103 | 104 | .. _Lift: http://liftweb.com 105 | 106 | -------------------------------------------------------------------------------- /naming_conventions/methods/index.rst: -------------------------------------------------------------------------------- 1 | .. Methods 2 | メソッド 3 | ------- 4 | 5 | .. Textual (alphabetic) names for methods should be in the camelCase style with the 6 | first letter lower-case:: 7 | 文章的な(アルファベットの)メソッド名は,小文字で始まるキャメルケースにします。 :: 8 | 9 | def myFairMethod = ... 10 | 11 | .. This section is not a comprehensive guide to idiomatic methods in Scala. Further 12 | information may be found in the method invocation section. 13 | この節はScalaにおける慣用的なメソッドの包括的なガイドではありません。更なる情報は「メソッド呼び出し」の節を見てください。 14 | 15 | .. toctree:: 16 | 17 | accessors_mutators 18 | parentheses 19 | operators 20 | -------------------------------------------------------------------------------- /naming_conventions/methods/operators.rst: -------------------------------------------------------------------------------- 1 | .. Operators 2 | 演算子 3 | ~~~~~~~~~ 4 | 5 | .. Avoid! Despite the degree to which Scala facilitates this area of API design, 6 | operator definition should not be undertaken lightly, particularly when the 7 | operator itself is non-standard (for example, ``>>#>>``). As a general rule, 8 | operators have two valid use-cases: 9 | 使わないように!Scalaが演算子を用いたAPI設計をどの程度サポートしているかは別にして,演算子の定義\ 10 | は軽々しく手を出すべきではありません。その演算子が一般的では無い場合(例えば,\ ``>>#>>``\ )は特にそうです。 11 | 一般的なルールとして,演算子には2つの適切なユースケースがあります。 12 | 13 | .. * Domain-specific languages (e.g. ``actor1 ! Msg``) 14 | * Logically mathematical operations (e.g. ``a + b`` or ``c :: d``) 15 | * ドメイン特化言語(e.g. ``actor1 ! Msg``\ ) 16 | * 論理的,数学的な演算(e.g. ``a + b``\ や\ ``c :: d``\ ) 17 | 18 | .. In the former case, operators may be used with impunity so long as the syntax is 19 | actually beneficial. However, in the course of standard API design, operators 20 | should be strictly reserved for purely-functional operations. Thus, it is 21 | acceptable to define a ``>>=`` operator for joining two monads, but it is not 22 | acceptable to define a ``<<`` operator for writing to an output stream. The 23 | former is mathematically well-defined and side-effect free, while the latter is 24 | neither of these. 25 | 前者のケースでは,構文が本当に有益な限りは演算子を使用しても構いません。\ 26 | しかしながら,通常のAPI設計の間は,演算子は純粋関数的な演算に限定して取っておくべきです。\ 27 | 従って,\ ``>>=``\ 演算子を2つのモナドを合成する目的で定義する事は構いませんが,\ ``<<``\ 演算子をアウトプットストリームに\ 28 | 書き出す用途で定義する事は認められません。\ 29 | 前者は数学的に明確に定義されていて副作用がありませんが,後者はそのどちらにもあてはまりません。 30 | 31 | .. Operator definition should be considered an advanced feature in Scala, to be used 32 | only by those most well-versed in its pitfalls. Without care, excessive operator 33 | overloading can easily transform even the simplest code into symbolic soup. 34 | Scalaでは演算子の定義はその危険性を良く理解した上級者のみが使うような高等な機能として考えられています。\ 35 | 注意しないと,過度の演算子オーバーロードは単純極まりないコードをも記号の嵐にしてしまいます。 36 | 37 | -------------------------------------------------------------------------------- /naming_conventions/methods/parentheses.rst: -------------------------------------------------------------------------------- 1 | .. Parentheses 2 | 括弧 3 | ~~~~~~~~~~~ 4 | 5 | .. Unlike Ruby, Scala attaches significance to whether or not a method is *declared* 6 | with parentheses (only applicable to methods of arity_-0). For example:: 7 | Rubyとは違い,Scalaはメソッドが括弧を伴って\ **宣言されている**\ かどうか(引数が無いメソッドにのみ該当します)\ 8 | に意味を持たせています。例えば, :: 9 | 10 | def foo1() = ... 11 | 12 | def foo2 = ... 13 | 14 | .. These are different methods at compile-time. While ``foo1`` can be 15 | called with or without the parentheses, ``foo2`` *may not* be called 16 | *with* parentheses. 17 | これらはコンパイル時に事なるメソッドとして解釈されます。\ ``foo1``\ は括弧があろうと無かろうと呼び出す事ができますが,\ 18 | ``foo2``\ は括弧\ **あり**\ では呼び出す事が\ **できません**\ 。 19 | 20 | .. Thus, it is actually quite important that proper guidelines be observed regarding 21 | when it is appropriate to declare a method without parentheses and when it is 22 | not. 23 | 従って,メソッド宣言をいつ括弧ありでするべきか,またいつ括弧無しでするべきかについてのガイドラインに従う事が非常に重要です。 24 | 25 | .. Methods which act as accessors of any sort (either encapsulating a field or a 26 | logical property) should be declared *without* parentheses except if they have side effects. 27 | While Ruby and Lift use a ``!`` to indicate this, the usage of parens is preferred [#dsl_note]_. 28 | アクセッサ(フィールドでも,論理プロパティでも)として働くメソッドは,副作用がある場合を除いて括弧\ **なし**\ で宣言するべきです。\ 29 | RubyとLiftは\ ``!``\ を使って副作用があることを示しますが,括弧の使用の方が好ましいです\ [#dsl_note]_\ 。 30 | 31 | .. Further, the callsite should follow the declaration; if declared with parentheses, 32 | call with parentheses. While there is temptation to save a few characters, 33 | if you follow this guideline, your code will be *much* more readable and 34 | maintainable. 35 | さらには,呼び出し側は宣言に従うべきです。つまり,括弧付きで定義されていれば括弧付きで呼び出すということです。\ 36 | わずかな文字数であっても節約したくなる誘惑にかられるかもしれませんが,このガイドラインに従えばコードは\ **とても**\ 読みやすく,\ 37 | メンテナンスしやすくなります。 38 | 39 | :: 40 | 41 | // 状態は変えません。birthdateの形で呼びます。 42 | def birthdate = firstName 43 | 44 | // 内部状態を更新します。age()の形で呼びます。 45 | def age() = { 46 | _age = updateAge(birthdate) 47 | _age 48 | } 49 | 50 | .. _arity: http://en.wikipedia.org/wiki/Arity 51 | 52 | .. rubric:: 脚注 53 | 54 | .. .. [#dsl_note] Please note that fluid APIs and internal domain-specific languages have a 55 | tendency to break the guidelines given below for the sake of syntax. Such 56 | exceptions should not be considered a violation so much as a time when these 57 | rules do not apply. In a DSL, syntax should be paramount over convention. 58 | .. [#dsl_note] 流れるようなAPIと内部DSLには,構文のため以下で提供するガイドラインを破る傾向があります。\ 59 | このような例外は規約違反として考えるべきではありません。\ 60 | DSLでは,構文が最も重要であり,規約に優先します。 61 | -------------------------------------------------------------------------------- /naming_conventions/objects.rst: -------------------------------------------------------------------------------- 1 | .. Objects 2 | オブジェクト 3 | ------- 4 | 5 | .. Objects follow the class naming convention (camelCase with a capital first letter) 6 | except when attempting to mimic a package. This is a fairly rare case, but it 7 | does come up on occasion:: 8 | オブジェクトは,クラスの命名規約(大文字始まりのキャメルケース)に従います。ただし,パッケージを模したオブジェクトは除きます。\ 9 | かなり稀なケースですが,まさにこれが必要となる場合があります。 :: 10 | 11 | object ast { 12 | sealed trait Expr 13 | 14 | case class Plus(e1: Expr, e2: Expr) extends Expr 15 | ... 16 | } 17 | 18 | .. In *all* other cases, objects should be named according to the class naming 19 | convention. 20 | その他\ **全ての**\ ケースでは,オブジェクトはクラスの命名規則に従います。 21 | 22 | -------------------------------------------------------------------------------- /naming_conventions/packages.rst: -------------------------------------------------------------------------------- 1 | .. Packages 2 | パッケージ 3 | -------- 4 | 5 | .. Scala packages should follow the Java package naming conventions:: 6 | ScalaのパッケージはJavaにおけるパッケージの命名規則に従います。:: 7 | 8 | // 誤り! 9 | package coolness 10 | 11 | // 正しい! 12 | package com.novell.coolness 13 | 14 | // パッケージオブジェクトcom.novell.coolnessとして正しい。 15 | package com.novell 16 | /** 17 | * coolnessに関連したクラスを提供する。 18 | */ 19 | package object coolness { 20 | } 21 | 22 | 23 | 24 | .. Versions Prior to 2.8 25 | 2.8以前のバージョン 26 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 27 | 28 | .. Scala 2.8 changes how packages worked. For 2.7 and earlier, 29 | please note that this convention does occasionally lead to problems when combined 30 | with Scala's nested packages feature. For example:: 31 | Scala2.8でパッケージの動作は変更されました。2.7以前のバージョンでは,ネストしたパッケージと組み合わさった時に\ 32 | 時折問題を起こす事があることに気をつけてください。 :: 33 | 34 | import net.liftweb._ 35 | 36 | .. This import will actually fail to resolve in some contexts as the ``net`` package 37 | may refer to the ``java.net`` package (or similar). To compensate for this, it 38 | is often necessary to fully-qualify imports using the ``_root_`` directive, 39 | overriding any nested package resolves:: 40 | このimport文は,\ ``net``\ パッケージが\ ``java.net``\ パッケージ(や同様のもの)を参照してしまい,解決に失敗するでしょう。\ 41 | この動作を補正するには,\ ``_root``\ ディレクティブを使って,ネストしたパッケージ解決を上書きしてimport文を完全修飾する事が\ 42 | 必要になります。 :: 43 | 44 | import _root_.net.liftweb._ 45 | 46 | .. Do not overuse this directive. In general, nested package resolves are a good 47 | thing and very helpful in reducing import clutter. Using ``_root_`` not only 48 | negates their benefit, but also introduces extra clutter in and of itself. 49 | このディレクティブを多用しないでください。一般に,ネストしたパッケージ解決は煩雑なimport文を減らす優れた手段となります。\ 50 | \ ``_root_``\ を使うと,その利点を帳消しにするだけでなく,更に乱雑なimport文を増やす結果になってしまいます。 51 | 52 | -------------------------------------------------------------------------------- /naming_conventions/special_note_on_brevity.rst: -------------------------------------------------------------------------------- 1 | .. Special Note on Brevity 2 | 表現の簡潔さに関する特記事項 3 | ----------------------- 4 | 5 | .. Because of Scala's roots in the functional languages, it is quite normal for 6 | local field names to be extremely brief:: 7 | 関数型言語をその背景に持つことから,Scalaではローカルフィールドの名前が非常にそっけない事は日常茶飯事です。 :: 8 | 9 | def add(a: Int, b: Int) = a + b 10 | 11 | .. While this would be bad practice in languages like Java, it is *good* practice 12 | in Scala. This convention works because properly-written Scala methods are 13 | quite short, only spanning a single expression and rarely going beyond a few 14 | lines. Very few local fields are ever used (including parameters), and so there 15 | is no need to contrive long, descriptive names. This convention substantially 16 | improves the brevity of most Scala sources. 17 | Javaの様な言語ではこれは良くない慣習とされていますが,Scalaにおいては\ **良い**\ 習慣です。\ 18 | この規約が奏功する理由は,適切に書かれたScalaのメソッドは,単一の式で,稀に数行に渡る程度で相当に短くなるためです。\ 19 | ローカルフィールドはおよそ使われることは無いため,長く記述的な名称を設計する必要はありません。\ 20 | この規約は殆どのScalaソースコードの簡潔性を大いに向上します。 21 | 22 | .. This convention only applies to parameters of very simple methods (and local fields for 23 | very simply classes); everything in the public interface should be descriptive. 24 | この規約はとてもシンプルなメソッド(と非常にシンプルなクラスのフィールド)の引数にのみ適用されます。\ 25 | パブリックインターフェースの要素はすべからく記述的たるべきです。 26 | -------------------------------------------------------------------------------- /naming_conventions/type_aliases.rst: -------------------------------------------------------------------------------- 1 | .. Type Aliases 2 | 型エイリアス 3 | ------------ 4 | 5 | .. Type aliases follow the same naming conventions as classes. For example:: 6 | 型エイリアスはクラスと同様の命名規約に従います。例えば次の様にします。 :: 7 | 8 | type StringList = List[String] 9 | 10 | 11 | -------------------------------------------------------------------------------- /naming_conventions/type_parameters/higher_kinds.rst: -------------------------------------------------------------------------------- 1 | .. Higher-Kinds 2 | 高階型 3 | ~~~~~~~~~~~~ 4 | 5 | .. While higher-kinds are theoretically no different from regular type parameters 6 | (except that their kind_ is at least ``*=>*`` rather than simply ``*``), their 7 | naming conventions do differ somewhat. Generally, higher-kinded parameters are 8 | two upper-case characters, usually repeated. For example:: 9 | 理論的には,高階型変数は通常の型変数と何ら変わりありません(その\ 種_\ が単純な\ ``*``\ ではなく,\ 10 | 少なくとも\ ``* => *``\ である場合を除いて)が,その命名規約はいくらか異なります。\ 11 | 一般に,高階型変数は大文字2文字で,普通は同じ文字を2文字重ねます。例えば,次の様になります。 :: 12 | 13 | class HOMap[AA[_], BB[_]] { ... } 14 | 15 | .. It is also (sometimes) acceptable to give full, descriptive names to higher-kinded 16 | parameters. In this case, use all-caps to make it clear you are not referring 17 | to a class or trait. Thus, the following would be an equally valid definition of ``HOMap``:: 18 | 高階型変数は,時に完全に記述的な名称が使われる事もあります。この場合,クラスやトレイトを参照しているのでは無いことを\ 19 | 明確にするため,全て大文字で記述します。したがって,次の例もまた等価な\ ``HOMap``\ の定義となります。 :: 20 | 21 | class HOMap[KEY[_], VALUE[_]] { ... } 22 | 23 | .. In such cases, the type naming conventions should be observed. 24 | 高階型変数を持つ場合も,型の命名規約は遵守するべきです。 25 | 26 | .. _種: http://en.wikipedia.org/wiki/Kind_(type_theory) 27 | 28 | -------------------------------------------------------------------------------- /naming_conventions/type_parameters/index.rst: -------------------------------------------------------------------------------- 1 | .. Type Parameters (generics) 2 | 型パラメータ(ジェネリクス) 3 | -------------------------- 4 | 5 | .. Type parameters are typically a single upper-case letter (from the English 6 | alphabet). Conventionally, parameters blindly start at ``A`` and ascend up to 7 | ``Z`` as necessary. This contrasts with the Java convention of using ``T``, ``K``, 8 | ``V`` and ``E``. For example:: 9 | 型パラメータは,通常大文字1文字(英語のアルファベット)で書きます。\ 10 | 慣例として,\ ``A``\ から始まり必要に応じて\ ``Z``\ まで順に使っていきます。\ 11 | \ ``T``\ ,\ ``K``\ ,\ ``V``\ ,\ ``K``\ などを使うJavaとは対照的です。例えば次の様に書きます。 :: 12 | 13 | class List[A] { 14 | def map[B](f: A => B): List[B] = ... 15 | } 16 | 17 | .. toctree:: 18 | 19 | higher_kinds 20 | -------------------------------------------------------------------------------- /nested_blocks/curly_braces.rst: -------------------------------------------------------------------------------- 1 | .. Curly Braces 2 | 波括弧 3 | ------------ 4 | 5 | .. Opening curly braces (``{``) must be on the same line as the declaration they 6 | represent:: 7 | 左波括弧(\ ``{``\ )は,その宣言と同じ行に置きます。 :: 8 | 9 | def foo = { 10 | ... 11 | } 12 | 13 | .. Technically, Scala's parser *does* support GNU-style notation with opening braces 14 | on the line following the declaration. However, the parser is not terribly 15 | predictable when dealing with this style due to the way in which semi-colon 16 | inference is implemented. Many headaches will be saved by simply following the 17 | curly brace convention demonstrated above. 18 | 技術的には,ScalaのパーサはGNUスタイルの,つまり,宣言の次の行に左括弧を配置する記法をサポート\ **します**\ 。\ 19 | しかし,Scalaパーサのセミコロン推論の実装方法の制限から,このスタイルで書かれた場合には推論がうまくできません。\ 20 | 上述の規約に従うことで,悩みの種は殆ど無くなります。 21 | 22 | 23 | -------------------------------------------------------------------------------- /nested_blocks/index.rst: -------------------------------------------------------------------------------- 1 | .. Nested Blocks 2 | ネストしたブロック 3 | ============= 4 | 5 | .. toctree:: 6 | 7 | curly_braces 8 | parentheses 9 | -------------------------------------------------------------------------------- /nested_blocks/parentheses.rst: -------------------------------------------------------------------------------- 1 | .. Parentheses 2 | 丸括弧 3 | ----------- 4 | 5 | .. In the rare cases when parenthetical blocks wrap across lines, the opening and 6 | closing parentheses should be unspaced and kept on the same lines as their content 7 | (Lisp-style):: 8 | 稀なケースですが,丸括弧で囲まれたブロックが複数行に渡る場合,括弧とその中身はスペースを置かず,\ 9 | 同じ行に配置します(Lispスタイル)。 :: 10 | 11 | (this + is a very ++ long * 12 | expression) 13 | 14 | .. The only exception to this rule is when defining grammars using parser combinators:: 15 | パーサコンビネータを使って文法規則を定義するときが,唯一の例外になります。 :: 16 | 17 | lazy val e: Parser[Int] = ( 18 | e ~ "+" ~ e ^^ { (e1, _, e2) => e1 + e2 } 19 | | e ~ "-" ~ e ^^ { (e1, _, e2) => e1 - e2 } 20 | | """\d+""".r ^^ { _.toInt } 21 | ) 22 | 23 | .. Parser combinators are an internal DSL, however, meaning that many of these style 24 | guidelines are inapplicable. 25 | パーサコンビネータは内部DSLですが,これはつまりスタイルガイドラインの多くが意味を成さないという事です。 26 | 27 | 28 | -------------------------------------------------------------------------------- /overview.rst: -------------------------------------------------------------------------------- 1 | .. Overview 2 | 概要 3 | ======== 4 | 5 | .. Generally speaking, Scala seeks to mimic Java conventions to ease interoperability. 6 | When in doubt regarding the idiomatic way to express a particular concept, adopt 7 | conventions and idioms from the following languages (in this order): 8 | 相互運用性の容易性を確保するため,一般にScalaはJavaの規約を真似ています。\ 9 | 特定の概念におけるイディオムがある場合には,規約とイディオムを次の言語から採用しています(この順番で)。 10 | 11 | 12 | * Java 13 | * `Standard ML`_ 14 | * Haskell 15 | * C# 16 | * OCaml 17 | * Ruby 18 | * Python 19 | 20 | 例えば,クラスやメソッドの命名では,SMLの型注釈やHaskellの型パラメータ(大文字では無く小文字を使う),\ 21 | またRubyの非ブーリアン値へのアクセサメソッドの命名規約では無く,Javaの規約に従うべきです。\ 22 | Scalaは正にハイブリッド言語と言えるでしょう! 23 | 24 | 25 | .. For example, you should use Java's naming conventions for classes and methods, 26 | but SML's conventions for type annotation, Haskell's conventions for type 27 | parameter naming (except upper-case rather than lower) and Ruby's conventions for 28 | non-boolean accessor methods. Scala really is a hybrid language! 29 | 30 | .. _Standard ML: http://en.wikipedia.org/wiki/Standard_ML 31 | 32 | -------------------------------------------------------------------------------- /refcard.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | 3 | require 'rubygems' 4 | # Later versions don't respect leading whitespace, which 5 | # messes up all the formatting 6 | gem 'prawn', '=0.6.3' 7 | require 'prawn' 8 | require 'prawn/measurement_extensions' 9 | 10 | def body(doc) 11 | doc.font("./Georgia.ttf") 12 | doc.font_size(10) 13 | end 14 | 15 | def code(doc) 16 | doc.font("./VeraMono.ttf") 17 | doc.font_size(8) 18 | end 19 | 20 | def head(doc) 21 | doc.font("./Georgia.ttf") 22 | doc.font_size(20) 23 | end 24 | 25 | def sub(doc) 26 | doc.font("./Georgia.ttf") 27 | doc.font_size(14) 28 | end 29 | doc = Prawn::Document.new(:page_layout => :landscape, 30 | :page_size => "LETTER", 31 | :left_margin => 0.5.in, 32 | :right_margin => 0.5.in, 33 | :bottom_margin => 0.5.in, 34 | :top_margin => 0.5.in) 35 | 36 | doc.bounding_box([0,7.5.in], :width => 10.in, :height => 24) do 37 | head(doc) 38 | doc.text("Scala Style Reference Card", :align => :center) 39 | end 40 | doc.column_box([0,7.5.in - 24], :width => 10.in, :height => 7.5.in - 24, :columns => 3) do 41 | sub(doc) 42 | doc.text("Indenting & Spacing") 43 | code(doc) 44 | doc.text < Int) 64 | 65 | EOS 66 | sub(doc) 67 | doc.text("Braces & Parens") 68 | code(doc) 69 | doc.text < "no need for braces" 84 | case "more complex" => { 85 | "consider" 86 | "using braces" 87 | } 88 | } 89 | 90 | // keep parens with code, LISP-style 91 | val y = (4 + foo + 6 + 92 | bar(x) + 17) 93 | 94 | // no parens for Arity-1 95 | def method(f: Int => Float) 96 | 97 | // parens for anything else 98 | def method(f: (Int,Double) => Float) 99 | 100 | EOS 101 | sub(doc) 102 | doc.text("Naming") 103 | code(doc) 104 | doc.text < a + b } 172 | 173 | // unless really really short 174 | val tight = (Int,Int) => _ + _ 175 | 176 | // Let Scala infer str's type 177 | someList map { str => str.toInt } 178 | 179 | // short duck types on one line 180 | def duck(a: { def close():Unit }) 181 | 182 | // for longer, make a type alias 183 | private type Closeable = { 184 | def open(r:Resource) 185 | def close:Resource 186 | } 187 | def duck(a: Closeable) 188 | 189 | class WorstCase( 190 | for:Long 191 | class:Declaration 192 | is:ToWrap) 193 | extends Sensible 194 | with FourSpaces 195 | with Judgement { 196 | } 197 | 198 | // handy for call-site 199 | def higherOrder(a:Int)(curryLast: Int => Int) 200 | 201 | EOS 202 | sub(doc) 203 | doc.text("General") 204 | code(doc) 205 | doc.text < 10.in, :height => 24) do 225 | head(doc) 226 | doc.text("Scala Style Reference Card", :align => :center) 227 | end 228 | 229 | sub(doc) 230 | doc.text("General (con't)") 231 | code(doc) 232 | doc.text < 5 } 248 | 249 | // symbolic operators always infix 250 | val all = some ++ others 251 | 252 | EOS 253 | 254 | sub(doc) 255 | doc.text("Scaladoc") 256 | code(doc) 257 | doc.text < val complex = Complex(4,3) 115 | * complex: my.package.complex.Complex = 4 + 3i 116 | * }}} 117 | * 118 | * If you include [[my.package.complex.ComplexConversions]], you can 119 | * convert numbers more directly 120 | * {{{ 121 | * scala> import my.package.complex.ComplexConversions._ 122 | * scala> val complex = 4 + 3.i 123 | * complex: my.package.complex.Complex = 4 + 3i 124 | * }}} 125 | */ 126 | package complex {} 127 | 128 | .. Classes, Objects, and Traits 129 | クラス,オブジェクト,トレイト 130 | ---------------------------- 131 | 132 | .. Document all classes, objects, and traits. The first sentence of the scaladoc should provide a summary of what 133 | the class or trait does. Document all type parameters with ``@tparam``. 134 | クラス,オブジェクト,トレイトは全てドキュメント化するべきです。最初のセンテンスでは,そのクラスやトレイトが何をするのかを要約して書きます。型パラメータは全て\ ``@tparam``\ でドキュメント化しましょう。 135 | 136 | 137 | .. Classes 138 | クラス 139 | ~~~~~~~ 140 | 141 | .. If a class should be created using it's companion object, indicate as such after the description of the class 142 | (though leave the details of construction to the companion object). Unfortunately, there is currently 143 | no way to create a link to the companion object inline, however the generated scaladoc will create a link 144 | for you in the class documentation output. 145 | そのコンパニオンオブジェクトを使ってクラスのインスタンス生成を行う場合,そのクラスの説明の後にその旨を記述してください\ 146 | (インスタンス生成に関する詳細はコンパニオンオブジェクトに記述します)。あいにく,今のところコンパニオンオブジェクトへの\ 147 | リンクをインラインで作る方法はありませんが,生成されたscaladocのクラスドキュメントにはリンクが作られます。 148 | 149 | .. If the class should be created using a constructor, document it using the ``@constructor`` syntax:: 150 | コンストラクタを使ってクラスのインスタンス生成を行うのであれば,\ ``@constructor``\ を使ってそれをドキュメント化しましょう。 :: 151 | 152 | /** 153 | * A person who uses our application. 154 | * 155 | * @constructor create a new person with a name and age. 156 | * @param name the person's name 157 | * @param age the person's age in years 158 | */ 159 | class Person(name:String, age:Int) { 160 | } 161 | 162 | .. Depending on the complexity of your class, provide an example of common usage. 163 | クラスが複雑であれば,一般的な利用例も書いておきましょう。 164 | 165 | .. Objects 166 | オブジェクト 167 | ~~~~~~~ 168 | 169 | .. Since objects can be used for a variety of purposes, it is important to document *how* to use the 170 | object (e.g. as a factory, for implicit methods). 171 | If this object is a factory for other objects, indicate as such here, deferring the specifics to 172 | the scaladoc for the ``apply`` method(s). If your object *doesn't* use ``apply`` as a factory 173 | method, be sure to indicate the actual method names:: 174 | オブジェクトは様々な用途に使えるので,\ **どのように**\ 使うか(e.g. ファクトリとして,implicitメソッドのため)を\ 175 | 書いておく事が重要です。そのオブジェクトの用途がファクトリなら,\ ``apply``\ メソッドに固有の記述を記述しましょう。\ 176 | もしオブジェクトが\ ``apply``\ メソッドをファクトリメソッドとして\ **使わない**\ のであれば,実際に使うメソッド名を\ 177 | 明記してください。 :: 178 | 179 | /** 180 | * Factory for [[mypackage.Person]] instances. 181 | */ 182 | object Person { 183 | /** Create a person with a given name and age. 184 | * @param name their name 185 | * @param age the age of the person to create 186 | */ 187 | def apply(name:String,age:Int) = {} 188 | /** Create a person with a given name and birthdate 189 | * @param name their name 190 | * @param birthDate the person's birthdate 191 | * @return a new Person instance with the age determined by the 192 | * birthdate and current date. 193 | */ 194 | def apply(name:String,birthDate:java.util.Date) = {} 195 | } 196 | 197 | .. If your object holds implicit conversions, provide an example in the scaladoc:: 198 | .. * 199 | 200 | オブジェクトに暗黙的変換メソッドがあれば,scaladocに利用例を示しましょう。 :: 201 | 202 | /** 203 | * Implicits conversions and helpers for [[mypackage.Complex]] instances. 204 | * 205 | * {{{ 206 | * import ComplexImplicits._ 207 | * val c:Complex = 4 + 3.i 208 | * }}} 209 | */ 210 | object ComplexImplicits {} 211 | 212 | .. Traits 213 | トレイト 214 | ~~~~~~ 215 | 216 | .. After the overview of what the trait does, provide an overview of the methods and types that must be 217 | specified in classes that mix in the trait. If there are known classes using the trait, reference them. 218 | トレイトが何をするかの概要を書いたら,そのトレイトをミックスインしたクラスが実装しなければならないメソッドと型の概要を\ 219 | 記述します。そのトレイトを利用している既存のクラスがあれば,参照して下さい。 220 | 221 | .. Methods and Other Members 222 | メソッドとその他のメンバ 223 | ------------------------- 224 | 225 | .. Document all methods. As with other documentable entities, the first sentence should be a summary of what the method does. 226 | Subsequent sentences explain in further detail. Document each parameter as well as each type parameter (with 227 | ``@tparam``). For curried functions, consider providing more detailed examples regarding the expected or 228 | idiomatic usage. For implicit parameters, take special to care to explain where these parameters will come from 229 | and if the user needs to do any extra work to make sure the parameters will be available. 230 | 全てのメソッドをドキュメント化してください。他と同様に,そのメソッドが何をするかを要約したものを最初に書きます。\ 231 | 続いて,更に詳細を書いていきます。型パラメータと同様に\ ``@tparam``\ を使ってメソッドパラメータもドキュメント化します。\ 232 | カリー化される関数は,期待する使用法や慣例的な使用法を考慮して,より詳細な例を提供することを検討してください。\ 233 | 暗黙のパラメータでは,そのパラメータがどこから来るのか,そしてそのパラメータを使うために特別な手続きが必要\ 234 | かどうかに特に注意してください。 235 | 236 | 237 | 238 | -------------------------------------------------------------------------------- /types/annotations.rst: -------------------------------------------------------------------------------- 1 | .. Annotations 2 | 型注釈 3 | ----------- 4 | 5 | .. Type annotations should be patterned according to the following template:: 6 | 型注釈は次のテンプレートに従って記述します。 :: 7 | 8 | value: Type 9 | 10 | .. This is the style adopted by most of the Scala standard library and all of 11 | Martin Odersky's examples. The space between value and type helps the eye in 12 | accurately parsing the syntax. The reason to place the colon at the end of the 13 | value rather than the beginning of the type is to avoid confusion in cases such 14 | as this one:: 15 | これは多くのScala標準ライブラリと,全てのMartin Odersky氏のコード例で採用されたスタイルです。\ 16 | 値と型の間のスペースは文法を目で追いやすくしてくれます。コロンを型の前では無く値の後ろに置くのは,\ 17 | 次の様な場合における混乱を避けるためです。 :: 18 | 19 | value ::: 20 | 21 | .. This is actually valid Scala, declaring a value to be of type ``::``. Obviously, 22 | the prefix-style annotation colon muddles things greatly. The other option is 23 | the "two space" syntax:: 24 | 実際,これは\ ``::``\ 型の値を宣言する妥当なScalaコードです。当然ながら,前置記法の型注釈によるコロンは大いに\ 25 | 混乱を引き起こします。もう1つ別の選択肢として,「スペース2つ」構文があります。 :: 26 | 27 | value : Type 28 | 29 | .. This syntax is preferable to the prefix-style, but it is not widely adopted due 30 | to its increased verbosity. 31 | この構文は前置記法よりも好ましいですが,その冗長性から広く採用されるには至っていません。 32 | 33 | -------------------------------------------------------------------------------- /types/ascription.rst: -------------------------------------------------------------------------------- 1 | .. Ascription 2 | みなし型 3 | ---------- 4 | 5 | .. Type ascription is often confused with type annotation, as the syntax in Scala 6 | is identical. The following are examples of ascription: 7 | Scalaではその文法が同じため,みなし型は型注釈とよく混同されます。次にみなし型の例を挙げます。 8 | 9 | * ``Nil: List[String]`` 10 | * ``Set(values: _*)`` 11 | * ``"Daniel": AnyRef`` 12 | 13 | .. Ascription is basically just an up-cast performed at compile-time for the sake of 14 | the type checker. Its use is not common, but it does happen on occasion. The 15 | most often seen case of ascription is invoking a varargs method with a single 16 | ``Seq`` parameter. This is done by ascribing the ``_*`` type (as in the second 17 | example above). 18 | 19 | みなしは,型チェックのためにコンパイル時に行われる単なるアップキャストと言えます。よく利用される訳ではありませんが,\ 20 | 場合によっては必要に迫られます。最もよく起こるケースが,可変長引数のメソッドを1つの\ ``Seq``\ パラメータで呼び出す時です。\ 21 | これは上記の2番目の例の様に,\ ``_*``\ 型を配置することで可能になります。 22 | 23 | .. Ascription follows the type annotation conventions; a space follows the colon. 24 | みなしは型注釈のコロンの後ろにスペースを置くという慣例に従います。 25 | -------------------------------------------------------------------------------- /types/functions/arity_1.rst: -------------------------------------------------------------------------------- 1 | .. Arity-1 2 | 1引数の関数型 3 | ~~~~~~~ 4 | 5 | .. Scala has a special syntax for declaring types for functions of arity-1. For 6 | example:: 7 | Scalaには1引数の関数を宣言するのに使われる特別なシンタックスがあります。例えば次のようなものです。 :: 8 | 9 | def map[B](f: A => B) = ... 10 | 11 | .. Specifically, the parentheses may be omitted from the parameter type. Thus, we 12 | did *not* declare ``f`` to be of type "``(A) => B``, as this would have been 13 | needlessly verbose. Consider the more extreme example:: 14 | 具体的に言うと,パラメータ型の括弧は省略する事ができます。そのため,不要に冗長になることを防ぐため,\ 15 | \ ``f``\ の型を\ ``(A) => B``\ として宣言しませんでした。より極端な例を考えてみると,次のようになります。 :: 16 | 17 | // 誤り! 18 | def foo(f: (Int) => (String) => (Boolean) => Double) = ... 19 | 20 | // 正しい! 21 | def foo(f: Int => String => Boolean => Double) = ... 22 | 23 | .. By omitting the parentheses, we have saved six whole characters and dramatically 24 | improved the readability of the type expression. 25 | 括弧を省略することによって,6文字の節約をし,劇的に型表現の可読性を上げることができました。 26 | -------------------------------------------------------------------------------- /types/functions/index.rst: -------------------------------------------------------------------------------- 1 | .. Functions 2 | 関数型 3 | --------- 4 | 5 | .. Function types should be declared with a space between the parameter type, the 6 | arrow and the return type:: 7 | 関数型は,引数の型,矢印と戻り値の型をスペースで区切って宣言します。 :: 8 | 9 | def foo(f: Int => String) = ... 10 | 11 | def bar(f: (Boolean, Double) => List[String]) = ... 12 | 13 | .. Parentheses should be omitted wherever possible (e.g. methods of arity-1, such 14 | as ``Int => String``). 15 | 括弧は,省略できる場所ではどこでもそうするべきです(e.g. \ ``Int => String``\ の様な1引数のメソッド)。 16 | 17 | .. toctree:: 18 | 19 | arity_1 20 | -------------------------------------------------------------------------------- /types/index.rst: -------------------------------------------------------------------------------- 1 | .. Types 2 | 型 3 | ===== 4 | 5 | .. toctree:: 6 | 7 | inference/index 8 | annotations 9 | ascription 10 | functions/index 11 | structural_types 12 | -------------------------------------------------------------------------------- /types/inference/function_values.rst: -------------------------------------------------------------------------------- 1 | .. Function Values 2 | 関数値 3 | ~~~~~~~~~~~~~~~ 4 | 5 | .. Function values support a special case of type inference which is worth calling 6 | out on its own:: 7 | 呼び出し時に役立つ,型推論の特殊なケースを関数値はサポートします。 :: 8 | 9 | val ls: List[String] = ... 10 | ls map { str => str.toInt } 11 | 12 | .. In cases where Scala already knows the type of the function value we are declaring, 13 | there is no need to annotate the parameters (in this case, ``str``). This is an 14 | intensely helpful inference and should be preferred whenever possible. Note that 15 | implicit conversions which operate on function values will nullify this inference, 16 | forcing the explicit annotation of parameter types. 17 | 宣言しようとしている関数値の型をScalaが既に知っていれば,パラメータに型注釈を付与する必要は\ 18 | ありません(上記例の場合,\ ``str``\ が該当)。これは非常に便利なので,最大限活用しましょう。\ 19 | ただし,関数値を対象とする暗黙の型変換は,この型推論を無効にする事に注意しましょう。 20 | 21 | -------------------------------------------------------------------------------- /types/inference/index.rst: -------------------------------------------------------------------------------- 1 | .. Inference 2 | 型推論 3 | --------- 4 | 5 | .. Use type inference as much as possible. You should almost never annotate the type 6 | of a ``val`` field as their type will be immediately evident in their value:: 7 | 可能な限り型推論は利用するべきです。\ ``val``\ フィールドの型はその値によって明白なため,型注釈を付けないようにしてください。 :: 8 | 9 | val name = "Daniel" 10 | 11 | .. However, type inference has a way of coming back to haunt you when used on 12 | non-trivial methods which are part of the public interface. Just for the sake 13 | of safety, you should annotate all public methods in your class. 14 | しかし,パブリックインターフェースの一端をなすメソッドの型が自明でない場合,型推論は困った結果を引き起こす事もあります。\ 15 | 安全性を考慮して,自分のクラスのパブリックメソッドには総じて型注釈をつけるべきです。 16 | 17 | .. toctree:: 18 | 19 | function_values 20 | void_methods 21 | -------------------------------------------------------------------------------- /types/inference/void_methods.rst: -------------------------------------------------------------------------------- 1 | .. "Void" Methods 2 | "Void"メソッド 3 | ~~~~~~~~~~~~~~ 4 | 5 | .. The exception to the "annotate everything public" rule is methods which return 6 | ``Unit``. *Any* method which returns ``Unit`` should be declared using Scala's 7 | syntactic sugar for that case:: 8 | \ ``Unit``\ 型を返すメソッドは,「全てをパブリックとする」ルールの例外です。\ **全ての**\ \ ``Unit``\ 型を返すメソッドは,\ 9 | このような場合のためのシンタックスシュガーを使って宣言するべきです。 :: 10 | 11 | def printName() { 12 | println("Novell") 13 | } 14 | 15 | .. This compiles into:: 16 | これは次のようにコンパイルされます。 :: 17 | 18 | def printName(): Unit = { 19 | println("Novell") 20 | } 21 | 22 | .. You should prefer the former style (without the annotation or the equals sign) 23 | as it reduces errors and improves readability. For the record, it is also 24 | possible (and encouraged!) to declare abstract methods returning ``Unit`` with an 25 | analogous syntax:: 26 | エラーを減らし,可読性を高めるため,前者のスタイル(型注釈,等号の無い)を使うべきです。\ 27 | 正確を期すため言っておくと,\ ``Unit``\ 型を返す抽象メソッドも次のように同様のシンタックスで\ 28 | 宣言することができます。否,するべきです! :: 29 | 30 | def printName() // abstract def for printName(): Unit 31 | 32 | -------------------------------------------------------------------------------- /types/structural_types.rst: -------------------------------------------------------------------------------- 1 | .. Structural Types 2 | 構造的部分型 3 | ---------------- 4 | 5 | .. Structural types should be declared on a single line if they are less than 50 6 | characters in length. Otherwise, they should be split across multiple lines and 7 | (usually) assigned to their own type alias:: 8 | 構造的部分型は,行が50文字よりも短く収まるのなら1行で定義するべきです。それより長くなるようであれば,\ 9 | 複数行に分けて,型エイリアスに代入して使います。 :: 10 | 11 | // 誤り! 12 | def foo(a: { def bar(a: Int, b: Int): String; val baz: List[String => String] }) = ... 13 | 14 | // 正しい! 15 | private type FooParam = { 16 | val baz: List[String => String] 17 | def bar(a: Int, b: Int): String 18 | } 19 | 20 | def foo(a: FooParam) = ... 21 | 22 | .. Simpler structural types (under 50 characters) may be declared and used inline:: 23 | 50文字に満たないシンプルな構造的部分型はインラインで定義して用いて構いません。 :: 24 | 25 | def foo(a: { val bar: String }) = ... 26 | 27 | .. When declaring structural types inline, each member should be separated by a 28 | semi-colon and a single space, the opening brace should be *followed* by a space 29 | while the closing brace should be *preceded* by a space (as demonstrated in both 30 | examples above). 31 | インラインで定義する場合は,上述の例でそうなっているように,その構造的部分型の要素はセミコロンと\ 32 | スペース1つで区切り,左波括弧の後ろと右波括弧の前にスペースを置きます。 33 | 34 | 35 | --------------------------------------------------------------------------------