diff --git a/_ba/tour/abstract-type-members.md b/_ba/tour/abstract-type-members.md index 9e577d7cda..b7034b6922 100644 --- a/_ba/tour/abstract-type-members.md +++ b/_ba/tour/abstract-type-members.md @@ -15,7 +15,7 @@ Trejtovi i apstraktne klase mogu imati apstraktne tipove kao članove. To znači da konkretne implementacije definišu stvarni tip. Slijedi primjer: -```tut +```scala mdoc trait Buffer { type T val element: T @@ -26,7 +26,7 @@ U gornjem primjeru smo definisali apstraktni tip `T`. On se koristi za opis člana `element`. Ovaj trejt možemo naslijediti u apstraktnoj klasi i dodati gornju granicu tipa za `T` da bi ga učinili preciznijim. -```tut +```scala mdoc abstract class SeqBuffer extends Buffer { type U type T <: Seq[U] @@ -40,7 +40,7 @@ mora biti podtip `Seq[U]` za neki novi apstraktni tip `U`. Trejtovi ili [klase](classes.html) s apstraktnim tip-članovima se često koriste u kombinaciji s instanciranjem anonimnih klasa. Radi ilustracije, pogledaćemo program koji radi s sekvencijalnim baferom koji sadrži listu integera: -```tut +```scala mdoc abstract class IntSeqBuffer extends SeqBuffer { type U = Int } @@ -61,7 +61,7 @@ Metoda `newIntSeqBuf` koristi anonimnu klasu kao implementaciju `IntSeqBuf` pos Često je moguće pretvoriti apstraktni tip-član u tipski parametar klase i obrnuto. Slijedi verzija gornjeg koda koji koristi tipske parametre: -```tut +```scala mdoc:nest abstract class Buffer[+T] { val element: T } diff --git a/_ba/tour/annotations.md b/_ba/tour/annotations.md index cccac64c35..24b17a9012 100644 --- a/_ba/tour/annotations.md +++ b/_ba/tour/annotations.md @@ -30,7 +30,7 @@ Redoslijed anotacijskih klauza nije bitan. Određene anotacije će uzrokovati pad kompajliranja ako određeni uslovi nisu ispunjeni. Npr, anotacija `@tailrec` osigurava da je metoda [tail-rekurzivna](https://en.wikipedia.org/wiki/Tail_call). Tail-rekurzija može zadržati memorijske zahtjeve konstantnim. Evo kako se koristi na metodi koja izračunava faktorijel: -```tut +```scala mdoc import scala.annotation.tailrec def factorial(x: Int): Int = { diff --git a/_ba/tour/basics.md b/_ba/tour/basics.md index 6204faa74b..bff0c133c4 100644 --- a/_ba/tour/basics.md +++ b/_ba/tour/basics.md @@ -30,7 +30,7 @@ Izrazi su izjave koje imaju vrijednost. ``` Rezultate izraza možete prikazati pomoću `println`. -```tut +```scala mdoc println(1) // 1 println(1 + 1) // 2 println("Hello!") // Hello! @@ -41,7 +41,7 @@ println("Hello," + " world!") // Hello, world! Rezultatima možete dodijeliti naziv pomoću ključne riječi `val`. -```tut +```scala mdoc val x = 1 + 1 println(x) // 2 ``` @@ -51,13 +51,13 @@ Referenciranje vrijednosti ne okida njeno ponovno izračunavanje. Vrijednosti se ne mogu mijenjati. -```tut:fail +```scala mdoc:fail x = 3 // Ovo se ne kompajlira. ``` Tipovi vrijednosti mogu biti (automatski) zaključeni, ali možete i eksplicitno navesti tip: -```tut +```scala mdoc:nest val x: Int = 1 + 1 ``` @@ -67,7 +67,7 @@ Primijetite da deklaracija tipa `Int` dolazi nakon identifikatora `x`. Također Varijable su kao vrijednosti, osim što ih možete promijeniti. Varijable se definišu ključnom riječju `var`. -```tut +```scala mdoc:nest var x = 1 + 1 x = 3 // Ovo se kompajlira jer je "x" deklarisano s "var" ključnom riječju. println(x * x) // 9 @@ -75,7 +75,7 @@ println(x * x) // 9 Kao i s vrijednostima, tip možete eksplicitno navesti ako želite: -```tut +```scala mdoc:nest var x: Int = 1 + 1 ``` @@ -86,7 +86,7 @@ Izraze možete kombinovati okružujući ih s `{}`. Ovo se naziva blok. Rezultat zadnjeg izraza u bloku je rezultat cijelog bloka, također. -```tut +```scala mdoc println({ val x = 1 + 1 x + 1 @@ -99,7 +99,7 @@ Funkcije su izrazi koji primaju parametre. Možete definisati anonimnu funkciju (bez imena) koja vraća cijeli broj plus jedan: -```tut +```scala mdoc (x: Int) => x + 1 ``` @@ -107,21 +107,21 @@ Na lijevoj strani `=>` je lista parametara. Na desnoj strani je izraz koji koris Funkcije možete i imenovati. -```tut +```scala mdoc val addOne = (x: Int) => x + 1 println(addOne(1)) // 2 ``` Funkcije mogu imati više parametara. -```tut +```scala mdoc val add = (x: Int, y: Int) => x + y println(add(1, 2)) // 3 ``` Ili bez parametara. -```tut +```scala mdoc val getTheAnswer = () => 42 println(getTheAnswer()) // 42 ``` @@ -132,7 +132,7 @@ Metode izgledaju i ponašaju se vrlo slično funkcijama, ali postoji nekoliko ra Metode se definišu ključnom riječju `def`. Nakon `def` slijedi naziv, lista parametara, povratni tip, i tijelo. -```tut +```scala mdoc:nest def add(x: Int, y: Int): Int = x + y println(add(1, 2)) // 3 ``` @@ -141,14 +141,14 @@ Primijetite da je povratni tip deklarisan _nakon_ liste parametara i dvotačke ` Metode mogu imati više listi parametara. -```tut +```scala mdoc def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier println(addThenMultiply(1, 2)(3)) // 9 ``` Ili bez listi parametara ikako. -```tut +```scala mdoc def name: String = System.getProperty("name") println("Hello, " + name + "!") ``` @@ -158,7 +158,7 @@ Postoje i neke druge razlike, ali zasad, možete misliti o njima kao nečemu sli Metode mogu imati višelinijske izraze također. {% scalafiddle %} -```tut +```scala mdoc def getSquareString(input: Double): String = { val square = input * input square.toString @@ -173,7 +173,7 @@ Zadnjo izraz u tijelu metode je povratna vrijednost metode. (Scala ima ključnu Klasu možete definisati ključnom riječju `class` praćenom imenom i parametrima konstruktora. -```tut +```scala mdoc class Greeter(prefix: String, suffix: String) { def greet(name: String): Unit = println(prefix + name + suffix) @@ -186,7 +186,7 @@ Ne prenosi nikakvu korisnu informaciju.) Instancu klase možete kreirati pomoću ključne riječi `new`. -```tut +```scala mdoc val greeter = new Greeter("Hello, ", "!") greeter.greet("Scala developer") // Hello, Scala developer! ``` @@ -198,13 +198,13 @@ Detaljniji pregled klasa biće dat [kasnije](classes.html). Scala ima poseban tip klase koji se zove "case" klasa. Po defaultu, case klase su nepromjenjive i porede se po vrijednosti. Možete ih definisati s `case class` ključnim riječima. -```tut +```scala mdoc case class Point(x: Int, y: Int) ``` Instancu case klase možete kreirati i bez ključne riječi `new`. -```tut +```scala mdoc val point = Point(1, 2) val anotherPoint = Point(1, 2) val yetAnotherPoint = Point(2, 2) @@ -212,7 +212,7 @@ val yetAnotherPoint = Point(2, 2) I porede se po vrijednosti. -```tut +```scala mdoc if (point == anotherPoint) { println(point + " and " + anotherPoint + " are the same.") } else { @@ -235,7 +235,7 @@ Objasnićemo ih u dubinu [kasnije](case-classes.html). Objekti su jedine instance svojih definicija. Možete misliti o njima kao singltonima svoje vlastite klase. Objekte možete definisati ključnom riječju `object`. -```tut +```scala mdoc object IdFactory { private var counter = 0 def create(): Int = { @@ -247,7 +247,7 @@ object IdFactory { Objektima možete pristupati referenciranjem njihovog imena. -```tut +```scala mdoc val newId: Int = IdFactory.create() println(newId) // 1 val newerId: Int = IdFactory.create() @@ -262,7 +262,7 @@ Trejtovi su tipovi koji sadrže polja i metode. Više trejtova se može kombino Definišu se pomoću `trait` ključne riječi. -```tut +```scala mdoc:nest trait Greeter { def greet(name: String): Unit } @@ -270,7 +270,7 @@ trait Greeter { Metode trejtova mogu imati defaultnu implementaciju. -```tut +```scala mdoc:reset trait Greeter { def greet(name: String): Unit = println("Hello, " + name + "!") @@ -279,7 +279,7 @@ trait Greeter { Možete naslijediti trejtove s `extends` ključnom riječi i redefinisati (override) implementacije s `override` ključnom riječi. -```tut +```scala mdoc class DefaultGreeter extends Greeter class CustomizableGreeter(prefix: String, postfix: String) extends Greeter { @@ -306,7 +306,7 @@ Java Virtuelna Mašina traži da se glavna metoda zove `main` i da prima jedan a Koristeći objekt, možete definisati glavnu metodu ovako: -```tut +```scala mdoc object Main { def main(args: Array[String]): Unit = println("Hello, Scala developer!") diff --git a/_ba/tour/by-name-parameters.md b/_ba/tour/by-name-parameters.md index e166f5242f..5cfc42f8cb 100644 --- a/_ba/tour/by-name-parameters.md +++ b/_ba/tour/by-name-parameters.md @@ -13,7 +13,7 @@ previous-page: operators _By-name parametri_ (u slobodnom prevodu "po-imenu parametri") se izračunavaju samo kada se koriste. Oni su kontrastu sa _by-value parametrima_ ("po-vrijednosti parametri"). Da bi parametar bio pozivan by-name, dodajte `=>` prije njegovog tipa. -```tut +```scala mdoc def calculate(input: => Int) = input * 37 ``` By-name parametri imaju prednost da se ne izračunavaju ako se ne koriste u tijelu funkcije. @@ -21,7 +21,7 @@ U drugu ruku, by-value parametri imaju prednost da se izračunavaju samo jednom. Ovo je primjer kako bi mogli implementirati while petlju: -```tut +```scala mdoc def whileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { body diff --git a/_ba/tour/case-classes.md b/_ba/tour/case-classes.md index a4cac6fad7..0c6de6d7b4 100644 --- a/_ba/tour/case-classes.md +++ b/_ba/tour/case-classes.md @@ -17,7 +17,7 @@ U sljedećem koraku turneje, vidjećemo kako su korisne u [podudaranju uzoraka ( ## Definisanje case klase Minimalna case klasa se sastoji iz ključnih riječi `case class`, identifikatora, i liste parametara (koja može biti prazna): -```tut +```scala mdoc case class Book(isbn: String) val frankenstein = Book("978-0486282114") diff --git a/_ba/tour/classes.md b/_ba/tour/classes.md index 534b1c6f27..29f170dca0 100644 --- a/_ba/tour/classes.md +++ b/_ba/tour/classes.md @@ -18,7 +18,7 @@ Tipovi, objekti i trejtovi biće pokriveni kasnije. ## Definisanje klase Minimalna definicija klase sastoji se od riječi `class` i identifikatora. Imena klasa bi trebala počinjati velikim slovom. -```tut +```scala mdoc class User val user1 = new User @@ -28,7 +28,7 @@ Ključna riječ `new` koristi se za kreiranje instance klase. Međutim, često ćete imati konstruktor i tijelo klase. Slijedi definicija klase `Point` (en. tačka): -```tut +```scala mdoc class Point(var x: Int, var y: Int) { def move(dx: Int, dy: Int): Unit = { @@ -56,7 +56,7 @@ Pošto `toString` prebrisava metodu `toString` iz [`AnyRef`](unified-types.html) Konstruktori mogu imati opcione parametre koristeći podrazumijevane vrijednosti: -```tut +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val origin = new Point // x and y are both set to 0 @@ -67,7 +67,7 @@ println(point1.x) // prints 1 U ovoj verziji klase `Point`, `x` i `y` imaju podrazumijevanu vrijednost `0` tako da ne morate proslijediti argumente. Međutim, pošto se argumenti konstruktora čitaju s lijeva na desno, ako želite proslijediti samo `y` vrijednost, morate imenovati parametar. -``` +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val point2 = new Point(y=2) println(point2.y) // prints 2 @@ -78,7 +78,7 @@ Ovo je također dobra praksa zbog poboljšanja čitljivosti. ## Privatni članovi i sintaksa getera/setera Članovi su javni (`public`) po defaultu. Koristite `private` modifikator pristupa da sakrijete članove klase. -```tut +```scala mdoc:nest class Point { private var _x = 0 private var _y = 0 @@ -108,14 +108,14 @@ Primijetite specijalnu sintaksu za setere: metoda ima `_=` nadodano na identifik Parametri primarnog konstruktora s `val` i `var` su javni. Međutim, pošto su `val` nepromjenjivi, ne možete napisati sljedeće. -``` +```scala mdoc:fail class Point(val x: Int, val y: Int) val point = new Point(1, 2) point.x = 3 // <-- does not compile ``` Parametri bez `val` ili `var` su privatne vrijednosti, vidljive samo unutar klase. -``` +```scala mdoc:fail class Point(x: Int, y: Int) val point = new Point(1, 2) point.x // <-- does not compile diff --git a/_ba/tour/compound-types.md b/_ba/tour/compound-types.md index 316d874c85..3781e866e3 100644 --- a/_ba/tour/compound-types.md +++ b/_ba/tour/compound-types.md @@ -15,7 +15,7 @@ U Scali ovo može biti izraženo pomoću *složenih tipova*, koji su presjeci ti Pretpostavimo da imamo dva trejta: `Cloneable` i `Resetable`: -```tut +```scala mdoc trait Cloneable extends java.lang.Cloneable { override def clone(): Cloneable = { super.clone().asInstanceOf[Cloneable] diff --git a/_ba/tour/default-parameter-values.md b/_ba/tour/default-parameter-values.md index 38be16bcc1..f4fc257900 100644 --- a/_ba/tour/default-parameter-values.md +++ b/_ba/tour/default-parameter-values.md @@ -13,7 +13,7 @@ prerequisite-knowledge: named-arguments, function syntax Scala omogućuje davanje podrazumijevanih vrijednosti parametrima koje dozvoljavaju korisniku metode da izostavi te parametre. -```tut +```scala mdoc def log(message: String, level: String = "INFO") = println(s"$level: $message") log("System starting") // prints INFO: System starting @@ -22,7 +22,7 @@ log("User not found", "WARNING") // prints WARNING: User not found Parametar `level` ima podrazumijevanu vrijednost tako da je opcioni. Na zadnjoj liniji, argument `"WARNING"` prebrisava podrazumijevani argument `"INFO"`. Gdje biste koristili overloadane metode u Javi, možete koristiti metode s opcionim parametrima da biste postigli isti efekat. Međutim, ako korisnik izostavi argument, bilo koji sljedeći argumenti moraju biti imenovani. -```tut +```scala mdoc class Point(val x: Double = 0, val y: Double = 0) val point1 = new Point(y = 1) @@ -31,7 +31,7 @@ Ovdje moramo reći `y = 1`. Podrazumijevani parametri u Scali nisu opcioni kada se koriste iz Java koda: -```tut +```scala mdoc:reset // Point.scala class Point(val x: Double = 0, val y: Double = 0) ``` diff --git a/_ba/tour/extractor-objects.md b/_ba/tour/extractor-objects.md index 979f2d4250..ac948e255d 100644 --- a/_ba/tour/extractor-objects.md +++ b/_ba/tour/extractor-objects.md @@ -14,7 +14,7 @@ Ekstraktor objekat je objekat koji ima `unapply` metodu. Dok je `apply` metoda kao konstruktor koji uzima argumente i kreira objekat, `unapply` metoda prima objekat i pokušava vratiti argumente. Ovo se najčešće koristi u podudaranju uzoraka i parcijalnim funkcijama. -```tut +```scala mdoc import scala.util.Random object CustomerID { @@ -41,7 +41,7 @@ Kada pozovemo `case CustomerID(name) => customer1ID`, ustvari pozivamo `unapply` Metoda `unapply` se može koristiti i za dodjelu vrijednosti. -```tut +```scala mdoc val customer2ID = CustomerID("Nico") val CustomerID(name) = customer2ID println(name) // prints Nico @@ -49,7 +49,7 @@ println(name) // prints Nico Ovo je ekvivalentno `val name = CustomerID.unapply(customer2ID).get`. Ako se uzorak ne podudari, baciće se `scala.MatchError` izuzetak: -```tut:fail +```scala mdoc:crash val CustomerID(name2) = "--asdfasdfasdf" ``` diff --git a/_ba/tour/for-comprehensions.md b/_ba/tour/for-comprehensions.md index efdeb57dc8..7064a95894 100644 --- a/_ba/tour/for-comprehensions.md +++ b/_ba/tour/for-comprehensions.md @@ -21,7 +21,7 @@ Komprehensija evaluira tijelo `e` za svako vezivanje varijable generisano od str Slijedi primjer: -```tut +```scala mdoc case class User(name: String, age: Int) val userBase = List(User("Travis", 28), @@ -38,7 +38,7 @@ twentySomethings.foreach(name => println(name)) // prints Travis Dennis Slijedi malo komplikovaniji primjer koji s dva generatora. Izračunava sve parove brojeva između `0` i `n-1` čija je suma jednaka vrijednosti `v`: -```tut +```scala mdoc def foo(n: Int, v: Int) = for (i <- 0 until n; j <- i until n if i + j == v) diff --git a/_ba/tour/generic-classes.md b/_ba/tour/generic-classes.md index c86d8f3f8f..63ce385f2c 100644 --- a/_ba/tour/generic-classes.md +++ b/_ba/tour/generic-classes.md @@ -19,7 +19,7 @@ Vrlo su korisne za implementiranje kolekcija. Generičke klase primaju tip kao parametar u uglastim zagradama `[]`. Konvencija je da se koristi slovo `A` kao identifikator tipa, mada se može koristiti bilo koje ime. -```tut +```scala mdoc class Stack[A] { private var elements: List[A] = Nil def push(x: A) { elements = x :: elements } diff --git a/_ba/tour/higher-order-functions.md b/_ba/tour/higher-order-functions.md index e7ac3103aa..8ddead84a5 100644 --- a/_ba/tour/higher-order-functions.md +++ b/_ba/tour/higher-order-functions.md @@ -14,7 +14,7 @@ Scala dozvoljava definisanje funkcija višeg reda. To su funkcije koje _primaju druge funkcije kao parametre_, ili čiji je _rezultat funkcija_. Ovo je funkcija `apply` koja uzima drugu funkciju `f` i vrijednost `v` i primjenjuje funkciju `f` na `v`: -```tut +```scala mdoc def apply(f: Int => String, v: Int) = f(v) ``` @@ -22,13 +22,13 @@ _Napomena: metode se automatski pretvaraju u funkcije ako to kontekst zahtijeva. Ovo je još jedan primjer: -```tut +```scala mdoc class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right } object FunTest extends App { - def apply(f: Int => String, v: Int) = f(v) + override def apply(f: Int => String, v: Int) = f(v) val decorator = new Decorator("[", "]") println(apply(decorator.layout, 7)) } diff --git a/_ba/tour/implicit-conversions.md b/_ba/tour/implicit-conversions.md index 090dc03323..d794590c45 100644 --- a/_ba/tour/implicit-conversions.md +++ b/_ba/tour/implicit-conversions.md @@ -43,7 +43,7 @@ Implicitno importovani objekt `scala.Predef` deklariše nekoliko predefinisanih Naprimjer, kada se pozivaju Javine metode koje očekuju `java.lang.Integer`, možete proslijediti `scala.Int`. Možete, zato što `Predef` uključuje slj. implicitnu konverziju: -```tut +```scala mdoc import scala.language.implicitConversions implicit def int2Integer(x: Int) = diff --git a/_ba/tour/implicit-parameters.md b/_ba/tour/implicit-parameters.md index 5b50d8f5e9..c39d87d626 100644 --- a/_ba/tour/implicit-parameters.md +++ b/_ba/tour/implicit-parameters.md @@ -22,7 +22,7 @@ Argumenti koji se mogu proslijediti kao implicitni parametri spadaju u dvije kat U sljedećem primjeru definisaćemo metodu `sum` koja izračunava sumu liste elemenata koristeći `add` i `unit` operacije monoida. Molimo primijetite da implicitne vrijednosti ne mogu biti top-level, već moraju biti članovi templejta. -```tut +```scala mdoc abstract class SemiGroup[A] { def add(x: A, y: A): A } diff --git a/_ba/tour/inner-classes.md b/_ba/tour/inner-classes.md index 41dd73ed91..10eac53bfb 100644 --- a/_ba/tour/inner-classes.md +++ b/_ba/tour/inner-classes.md @@ -17,7 +17,7 @@ Pretpostavimo da želimo da nas kompejler spriječi da pomiješamo koji čvorovi Radi ilustracije razlike, prikazaćemo implementaciju klase grafa: -```tut +```scala mdoc class Graph { class Node { var connectedNodes: List[Node] = Nil @@ -39,7 +39,7 @@ class Graph { U našem programu, grafovi su predstavljeni listom čvorova (`List[Node]`). Svaki čvor ima listu drugih čvorova s kojima je povezan (`connectedNodes`). Klasa `Node` je _path-dependent tip_ jer je ugniježdena u klasi `Graph`. Stoga, svi čvorovi u `connectedNodes` moraju biti kreirani koristeći `newNode` iz iste instance klase `Graph`. -```tut +```scala mdoc val graph1: Graph = new Graph val node1: graph1.Node = graph1.newNode val node2: graph1.Node = graph1.newNode @@ -54,7 +54,7 @@ Da imamo dva grafa, sistem tipova Scale ne dozvoljava miješanje čvorova defin jer čvorovi različitih grafova imaju različit tip. Ovo je primjer netačnog programa: -``` +```scala mdoc:fail val graph1: Graph = new Graph val node1: graph1.Node = graph1.newNode val node2: graph1.Node = graph1.newNode @@ -70,7 +70,7 @@ Za čvorove oba grafa, Java bi dodijelila isti tip `Graph.Node`; npr. `Node` bi U Scali takav tip je također moguće izraziti, piše se kao `Graph#Node`. Ako želimo povezati čvorove različitih grafova, moramo promijeniti definiciju naše inicijalne implementacije grafa: -```tut +```scala mdoc:nest class Graph { class Node { var connectedNodes: List[Graph#Node] = Nil diff --git a/_ba/tour/lower-type-bounds.md b/_ba/tour/lower-type-bounds.md index 8261a2e77c..85dd54a401 100644 --- a/_ba/tour/lower-type-bounds.md +++ b/_ba/tour/lower-type-bounds.md @@ -17,7 +17,7 @@ Izraz `B >: A` izražava tipski parametar `B` ili apstraktni tip `B` koji je nad Kroz sljedeći primjer vidjećemo zašto je ovo korisno: -```tut:fail +```scala mdoc:fail trait Node[+B] { def prepend(elem: B): Node[B] } @@ -43,7 +43,7 @@ Ovo ne radi jer su funkcije *kontra*varijantne u svojim tipovima parametara i *k Da bismo popravili ovo, moramo zamijeniti varijansu tipskog parametra `elem` u `prepend`. Ovo radimo uvođenjem novog tipskog parametra `U` koji ima `B` kao svoju donju granicu tipa. -```tut +```scala mdoc trait Node[+B] { def prepend[U >: B](elem: U): Node[U] } @@ -60,7 +60,7 @@ case class Nil[+B]() extends Node[B] { ``` Sada možemo uraditi sljedeće: -```tut +```scala mdoc trait Bird case class AfricanSwallow() extends Bird case class EuropeanSwallow() extends Bird diff --git a/_ba/tour/mixin-class-composition.md b/_ba/tour/mixin-class-composition.md index 66ad5f623e..a38c2ba2e1 100644 --- a/_ba/tour/mixin-class-composition.md +++ b/_ba/tour/mixin-class-composition.md @@ -13,7 +13,7 @@ prerequisite-knowledge: inheritance, traits, abstract-classes, unified-types Mixini su trejtovi koji se koriste za kompoziciju klase. -```tut +```scala mdoc abstract class A { val message: String } @@ -34,7 +34,7 @@ Klase mogu imati samo jednu nadklasu alid mogu imati više mixina (koristeći kl Pogledajmo sada zanimljiviji primjer počevši od apstraktne klase: -```tut +```scala mdoc abstract class AbsIterator { type T def hasNext: Boolean @@ -45,7 +45,7 @@ abstract class AbsIterator { Klasa ima apstraktni tip `T` i standardne metode iteratora. Dalje, implementiraćemo konkretnu klasu (svi apstraktni članovi `T`, `hasNext`, i `next` imaju implementacije): -```tut +```scala mdoc class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 @@ -66,7 +66,7 @@ class StringIterator(s: String) extends AbsIterator { Kreirajmo sada trejt koji također nasljeđuje `AbsIterator`. -```tut +```scala mdoc trait RichIterator extends AbsIterator { def foreach(f: T => Unit): Unit = while (hasNext) f(next()) } @@ -76,7 +76,7 @@ Pošto je `RichIterator` trejt, on ne mora implementirati apstraktne članove `A Željeli bismo iskombinirati funkcionalnosti `StringIterator`a i `RichIterator`a u jednoj klasi. -```tut +```scala mdoc object StringIteratorTest extends App { class Iter extends StringIterator("Scala") with RichIterator val iter = new Iter diff --git a/_ba/tour/multiple-parameter-lists.md b/_ba/tour/multiple-parameter-lists.md index ed9f22c1b1..68230aa12b 100644 --- a/_ba/tour/multiple-parameter-lists.md +++ b/_ba/tour/multiple-parameter-lists.md @@ -16,7 +16,7 @@ onda će to vratiti funkciju koja prima preostale liste parametara kao argumente Primjer: -```tut +```scala mdoc object CurryTest extends App { def filter(xs: List[Int], p: Int => Boolean): List[Int] = diff --git a/_ba/tour/named-arguments.md b/_ba/tour/named-arguments.md index abe434c3b4..6656b02da2 100644 --- a/_ba/tour/named-arguments.md +++ b/_ba/tour/named-arguments.md @@ -12,7 +12,7 @@ prerequisite-knowledge: function-syntax Kada se pozivaju metode, možete koristiti imena varijabli eksplicitno pri pozivu: -```tut +```scala mdoc def printName(first: String, last: String): Unit = { println(first + " " + last) } diff --git a/_ba/tour/nested-functions.md b/_ba/tour/nested-functions.md index 7c4adc75b2..1a00eaba59 100644 --- a/_ba/tour/nested-functions.md +++ b/_ba/tour/nested-functions.md @@ -13,7 +13,7 @@ previous-page: higher-order-functions U Scali je moguće ugnježdavati definicije metode. Sljedeći objekt sadrži metodu `factorial` za računanje faktorijela datog broja: -```tut +```scala mdoc def factorial(x: Int): Int = { def fact(x: Int, accumulator: Int): Int = { if (x <= 1) accumulator diff --git a/_ba/tour/operators.md b/_ba/tour/operators.md index 259fdca8fe..e16e338132 100644 --- a/_ba/tour/operators.md +++ b/_ba/tour/operators.md @@ -25,7 +25,7 @@ Međutim, lakše je čitati kada se napiše kao infiksni operator: ## Definisanje i korištenje operatora Možete koristiti bilo koji legalni identifikator kao operator. To uključuje i imena kao `add` ili simbole kao `+`. -```tut +```scala mdoc case class Vec(x: Double, y: Double) { def +(that: Vec) = Vec(this.x + that.x, this.y + that.y) } @@ -42,7 +42,7 @@ Koristeći zagrade, možete pisati kompleksne izraze s čitljivom sintaksom. Slijedi definicija klase `MyBool` koja definiše tri metode `and`, `or`, i `negate`. -```tut +```scala mdoc case class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that @@ -52,7 +52,7 @@ case class MyBool(x: Boolean) { Sada je moguće koristiti `and` i `or` kao infiksne operatore: -```tut +```scala mdoc def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) ``` diff --git a/_ba/tour/pattern-matching.md b/_ba/tour/pattern-matching.md index 6c902033a2..e303e05d63 100644 --- a/_ba/tour/pattern-matching.md +++ b/_ba/tour/pattern-matching.md @@ -16,7 +16,7 @@ Podudaranje uzoraka je mehanizam za provjeranje da li vrijednost odgovara uzroku ## Sintaksa Izraz za podudaranje ima vrijednost, `match` ključnu riječ, i bar jednu `case` klauzu. -```tut +```scala mdoc import scala.util.Random val x: Int = Random.nextInt(10) @@ -34,7 +34,7 @@ Zadnji slučaj, `_`, je "uhvati sve" slučaj za brojeve veće od 2. Slučajevi se još zovu i _alternative_. Izrazi za podudaranje imaju vrijednost. -```tut +```scala mdoc def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" @@ -50,7 +50,7 @@ Stoga, metoda `matchTest` vraća `String`. Case klase su posebno korisne za podudaranje uzoraka. -```tut +```scala mdoc abstract class Notification case class Email(sender: String, title: String, body: String) extends Notification @@ -118,7 +118,7 @@ U `case Email(email, _, _) if importantPeopleInfo.contains(email)`, uzorak se po ## Podudaranje samo tipa Možete podudarati samo tip ovako: -```tut +```scala mdoc abstract class Device case class Phone(model: String) extends Device { def screenOff = "Turning screen off" @@ -140,7 +140,7 @@ Konvencija je da se koristi prvo slovo tipa kao identifikator (`p` i `c` ovdje). Trejtovi i klase mogu biti `sealed` što znači da svi podtipovi moraju biti reklarisani u istom fajlu. Ovo osigurava da su svi podtipovi poznati. -```tut +```scala mdoc sealed abstract class Furniture case class Couch() extends Furniture case class Chair() extends Furniture diff --git a/_ba/tour/polymorphic-methods.md b/_ba/tour/polymorphic-methods.md index 2fcb672428..a5ad6e27f4 100644 --- a/_ba/tour/polymorphic-methods.md +++ b/_ba/tour/polymorphic-methods.md @@ -18,7 +18,7 @@ Vrijednosni parameteri ("obični") su ograđeni parom zagrada, dok su tipski par Slijedi primjer: -```tut +```scala mdoc def listOfDuplicates[A](x: A, length: Int): List[A] = { if (length < 1) Nil diff --git a/_ba/tour/regular-expression-patterns.md b/_ba/tour/regular-expression-patterns.md index 6936f74013..558b039a24 100644 --- a/_ba/tour/regular-expression-patterns.md +++ b/_ba/tour/regular-expression-patterns.md @@ -14,7 +14,7 @@ previous-page: singleton-objects Regularni izrazi su stringovi koji se mogu koristiti za traženje uzoraka u podacima. Bilo koji string se može pretvoriti u regularni izraz pozivom `.r` metode. -```tut +```scala mdoc import scala.util.matching.Regex val numberPattern: Regex = "[0-9]".r @@ -30,7 +30,7 @@ U gornjem primjeru, `numberPattern` je `Regex` Također, možete tražiti grupe regularnih izraza koristeći zagrade. -```tut +```scala mdoc import scala.util.matching.Regex val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r diff --git a/_ba/tour/self-types.md b/_ba/tour/self-types.md index da47a626bc..9b0ccd95a2 100644 --- a/_ba/tour/self-types.md +++ b/_ba/tour/self-types.md @@ -17,7 +17,7 @@ Self-tip je način da se suzi tip `this` ili drugi identifikator koji je alijas Sintaksa izgleda kao obična funkcija ali znači nešto sasvim drugačije. Da bi koristili self-tip u trejtu, napišite identifikator, tip drugog trejta za umiksavanje, i `=>` (tj. `someIdentifier: SomeOtherTrait =>`). -```tut +```scala mdoc trait User { def username: String } diff --git a/_ba/tour/singleton-objects.md b/_ba/tour/singleton-objects.md index 7c74f5318e..7f8ac84ba4 100644 --- a/_ba/tour/singleton-objects.md +++ b/_ba/tour/singleton-objects.md @@ -44,7 +44,7 @@ ako krug s velikim “C” ili “O” ima savijenu ivicu (kao papir), možete k Klasa i njen kompanjon objekt, ako ga ima, moraju biti definisani u istom izvornom fajlu: -```tut +```scala mdoc class IntPair(val x: Int, val y: Int) object IntPair { diff --git a/_ba/tour/traits.md b/_ba/tour/traits.md index 6d0356cda0..8f7a82cc9e 100644 --- a/_ba/tour/traits.md +++ b/_ba/tour/traits.md @@ -18,12 +18,12 @@ Klase i objekti mogu naslijediti trejtove ali trejtovi ne mogu biti instancirani ## Definisanje trejta Minimalni trejt je samo ključna riječ `trait` i identifikator: -```tut +```scala mdoc trait HairColor ``` Trejtovi su vrlo korisni s generičkim tipovima i apstraktnim metodama. -```tut +```scala mdoc trait Iterator[A] { def hasNext: Boolean def next(): A @@ -34,7 +34,7 @@ Nasljeđivanje `trait Iterator[A]` traži tip `A` i implementacije metoda `hasNe ## Korištenje trejtova Koristite `extends` za nasljeđivanje trejta. Zatim implementirajte njegove apstraktne članove koristeći `override` ključnu riječ: -```tut +```scala mdoc:nest trait Iterator[A] { def hasNext: Boolean def next(): A @@ -62,7 +62,7 @@ Ona nasljeđuje `Iterator[Int]` što znači da `next` mora vraćati `Int`. ## Podtipovi Podtipovi trejtova mogu se koristiti gdje se trejt traži. -```tut +```scala mdoc import scala.collection.mutable.ArrayBuffer trait Pet { diff --git a/_ba/tour/tuples.md b/_ba/tour/tuples.md index 34bceaa3d1..99f49e7247 100644 --- a/_ba/tour/tuples.md +++ b/_ba/tour/tuples.md @@ -10,4 +10,4 @@ previous-page: traits --- (this section of the tour has not been translated yet. pull request -with translation welcome!) \ No newline at end of file +with translation welcome!) diff --git a/_ba/tour/type-inference.md b/_ba/tour/type-inference.md index 3ff6ab6ce6..d3b7eb1867 100644 --- a/_ba/tour/type-inference.md +++ b/_ba/tour/type-inference.md @@ -16,7 +16,7 @@ Povratni tipovi metoda također mogu biti izostavljeni jer oni odgovaraju tipu t Slijedi jedan primjer: -```tut +```scala mdoc object InferenceTest1 extends App { val x = 1 + 2 * 3 // the type of x is Int val y = x.toString() // the type of y is String @@ -27,7 +27,7 @@ object InferenceTest1 extends App { Za rekurzivne metode, kompajler nije u mogućnosti da zaključi tip rezultata. Ovo je program koji se ne može kompajlirati iz ovog razloga: -```tut:fail +```scala mdoc:fail object InferenceTest2 { def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) } @@ -58,7 +58,7 @@ val y: Int = id[Int](1) U nekim situacijama može biti vrlo opasno osloniti se na Scalin mehanizam zaključivanja tipova: -```tut:fail +```scala mdoc:fail object InferenceTest4 { var obj = null obj = new Object() diff --git a/_ba/tour/unified-types.md b/_ba/tour/unified-types.md index 7f9787e5b9..c03e54ab0b 100644 --- a/_ba/tour/unified-types.md +++ b/_ba/tour/unified-types.md @@ -34,7 +34,7 @@ Ako se Scala koristi u kontekstu JRE, onda `AnyRef` odgovara klasi `java.lang.Ob Slijedi primjer koji demonstrira da su stringovi, integeri, karakteri, booleani i funkcije svi objekti kao bilo koji drugi: -```tut +```scala mdoc val list: List[Any] = List( "a string", 732, // an integer @@ -64,7 +64,7 @@ Vrijednosni tipovi mogu biti kastovani na sljedeći način: Npr: -```tut +```scala mdoc val x: Long = 987654321 val y: Float = x // 9.8765434E8 (određena doza preciznosti se gubi ovdje) diff --git a/_ba/tour/upper-type-bounds.md b/_ba/tour/upper-type-bounds.md index ce4f4e198e..e91d904d5d 100644 --- a/_ba/tour/upper-type-bounds.md +++ b/_ba/tour/upper-type-bounds.md @@ -15,7 +15,7 @@ Takve granice tipa ograničavaju konkretne vrijednosti tipskih varijabli i ponek _Gornja granica tipa_ `T <: A` kaže da se tipska varijabla `T` odnosi na podtip tipa `A`. Slijedi primjer koji demonstrira gornju granicu tipa za tipski parametar klase `PetContainer`: -```tut +```scala mdoc abstract class Animal { def name: String } @@ -42,7 +42,7 @@ val dogContainer = new PetContainer[Dog](new Dog) val catContainer = new PetContainer[Cat](new Cat) ``` -```tut:fail +```scala mdoc:fail val lionContainer = new PetContainer[Lion](new Lion) // this would not compile ``` Klasa `PetContainer` prima tipski parametar `P` koji mora biti podtip od `Pet`. diff --git a/_ba/tour/variances.md b/_ba/tour/variances.md index 0540982844..2920e00dac 100644 --- a/_ba/tour/variances.md +++ b/_ba/tour/variances.md @@ -14,7 +14,7 @@ Varijansa je korelacija podtipskih veza kompleksnih tipova i podtipskih veza nji Scala podržava anotacije varijanse tipskih parametara [generičkih klasa](generic-classes.html), dozvoljavajući im da budu kovarijantni, kontravarijantni, ili invarijantni ako se anotacije ne koriste. Korištenje varijanse u sistemu tipova dozvoljava pravljenje intuitivnijih veza među kompleksnim tipovima, a nedostatak varijanse može ograničiti ponovno iskorištenje klasne apstrakcije. -```tut +```scala mdoc class Foo[+A] // kovarijantna klasa class Bar[-A] // kontravarijantna klasa class Baz[A] // invarijantna klasa @@ -28,7 +28,7 @@ Ovo dozvoljava pravljenje vrlo intuitivnih podtipskih veza koristeći generiku. Razmotrite sljedeću strukturu klasa: -```tut +```scala mdoc abstract class Animal { def name: String } @@ -44,7 +44,7 @@ Intuitivno, ima smisla da su lista mačaka i lista pasa također liste životinj U sljedećem primjeru, metoda `printAnimalNames` prima listu životinja kao argument i ispisuje njihova imena, svako na idućoj liniji. Da `List[A]` nije kovarijantna, zadnja dva poziva metode se ne bi kompajlirali, što bi značajno ograničilo korisnost `printAnimalNames` metode. -```tut +```scala mdoc object CovarianceTest extends App { def printAnimalNames(animals: List[Animal]): Unit = { animals.foreach { animal => @@ -73,7 +73,7 @@ To jest, za neku `class Writer[-A]`, kontravarijantno `A` znači da za dva tipa Razmotrimo `Cat`, `Dog`, i `Animal` klase u sljedećem primjeru: -```tut +```scala mdoc abstract class Printer[-A] { def print(value: A): Unit } @@ -81,7 +81,7 @@ abstract class Printer[-A] { `Printer[A]` je jednostavna klasa koja zna ispisati neki tip `A`. Definišimo neke podklase za specifične tipove: -```tut +```scala mdoc class AnimalPrinter extends Printer[Animal] { def print(animal: Animal): Unit = println("The animal's name is: " + animal.name) @@ -99,7 +99,7 @@ Inverzna veza ne vrijedi, jer `Printer[Cat]` ne zna kako da ispiše bilo koju `A Stoga, terbali bismo moći zamijeniti `Printer[Animal]` za `Printer[Cat]`, ako želimo, i praveći `Printer[A]` kontravarijantnim nam to dozvoljava. -```tut +```scala mdoc object ContravarianceTest extends App { val myCat: Cat = Cat("Boots") @@ -129,7 +129,7 @@ Ovo znač da nisu ni kovarijantne ni kontravarijantne. U kontekstu sljedećeg primjera, `Container` klasa je invarijantna. `Container[Cat]` _nije_ `Container[Animal]`, niti obrnuto. -```tut +```scala mdoc class Container[A](value: A) { private var _value: A = value def getValue: A = _value @@ -162,7 +162,7 @@ Za ovaj primjer koristićemo literal notaciju `A => B` za predstavljanje `Functi Pretpostavimo da imamo sličnu hijerarhiju klasa `Cat`, `Dog`, `Animal` otprije, plus sljedeće: -```tut +```scala mdoc class SmallAnimal class Mouse extends SmallAnimal ``` diff --git a/_books/5-functional-programming-in-scala.md b/_books/5-functional-programming-in-scala.md index e90d36e92d..97a64d3a15 100644 --- a/_books/5-functional-programming-in-scala.md +++ b/_books/5-functional-programming-in-scala.md @@ -8,4 +8,4 @@ publisher: Manning publisherLink: https://www.manning.com/ --- -"Functional programming (FP) is a style of software development emphasizing functions that don't depend on program state... Functional Programming in Scala is a serious tutorial for programmers looking to learn FP and apply it to the everyday business of coding. The book guides readers from basic techniques to advanced topics in a logical, concise, and clear progression. In it, you'll find concrete examples and exercises that open up the world of functional programming." \ No newline at end of file +"Functional programming (FP) is a style of software development emphasizing functions that don't depend on program state... Functional Programming in Scala is a serious tutorial for programmers looking to learn FP and apply it to the everyday business of coding. The book guides readers from basic techniques to advanced topics in a logical, concise, and clear progression. In it, you'll find concrete examples and exercises that open up the world of functional programming." diff --git a/_es/tour/abstract-type-members.md b/_es/tour/abstract-type-members.md index ffcf7fd482..841fa8778e 100644 --- a/_es/tour/abstract-type-members.md +++ b/_es/tour/abstract-type-members.md @@ -14,56 +14,62 @@ previous-page: tour-of-scala En Scala, las cases son parametrizadas con valores (los parámetros de construcción) y con tipos (si las clases son [genéricas](generic-classes.html)). Por razones de consistencia, no es posible tener solo valores como miembros de objetos; tanto los tipos como los valores son miembros de objetos. Además, ambos tipos de miembros pueden ser concretos y abstractos. A continuación un ejemplo el cual define de forma conjunta una asignación de valor tardía y un tipo abstracto como miembros del [trait](traits.html) `Buffer`. - trait Buffer { - type T - val element: T - } +```scala mdoc +trait Buffer { + type T + val element: T +} +``` Los *tipos abstractos* son tipos los cuales su identidad no es precisamente conocida. En el ejemplo anterior, lo único que sabemos es que cada objeto de la clase `Buffer` tiene un miembro de tipo `T`, pero la definición de la clase `Buffer` no revela qué tipo concreto se corresponde con el tipo `T`. Tal como las definiciones de valores, es posible sobrescribir las definiciones de tipos en subclases. Esto permite revelar más información acerca de un tipo abstracto al acotar el tipo ligado (el cual describe las posibles instancias concretas del tipo abstracto). En el siguiente programa derivamos la clase `SeqBuffer` la cual nos permite almacenar solamente sequencias en el buffer al estipular que el tipo `T` tiene que ser un subtipo de `Seq[U]` para un nuevo tipo abstracto `U`: - abstract class SeqBuffer extends Buffer { - type U - type T <: Seq[U] - def length = element.length - } +```scala mdoc +abstract class SeqBuffer extends Buffer { + type U + type T <: Seq[U] + def length = element.length +} +``` Traits o [clases](classes.html) con miembros de tipos abstractos son generalmente usados en combinación con instancias de clases anónimas. Para ilustrar este concepto veremos un programa el cual trata con un buffer de sequencia que se remite a una lista de enteros. - abstract class IntSeqBuffer extends SeqBuffer { - type U = Int - } +```scala mdoc +abstract class IntSeqBuffer extends SeqBuffer { + type U = Int +} - object AbstractTypeTest1 extends App { - def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer = - new IntSeqBuffer { - type T = List[U] - val element = List(elem1, elem2) - } - val buf = newIntSeqBuf(7, 8) - println("length = " + buf.length) - println("content = " + buf.element) - } +object AbstractTypeTest1 extends App { + def newIntSeqBuf(elem1: Int, elem2: Int): IntSeqBuffer = + new IntSeqBuffer { + type T = List[U] + val element = List(elem1, elem2) + } + val buf = newIntSeqBuf(7, 8) + println("length = " + buf.length) + println("content = " + buf.element) +} +``` El tipo retornado por el método `newIntSeqBuf` está ligado a la especialización del trait `Buffer` en el cual el tipo `U` es ahora equivalente a `Int`. Existe un tipo alias similar en la instancia de la clase anónima dentro del cuerpo del método `newIntSeqBuf`. En ese lugar se crea una nueva instancia de `IntSeqBuffer` en la cual el tipo `T` está ligado a `List[Int]`. Es necesario notar que generalmente es posible transformar un tipo abstracto en un tipo paramétrico de una clase y viceversa. A continuación se muestra una versión del código anterior el cual solo usa tipos paramétricos. - abstract class Buffer[+T] { - val element: T - } - abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] { - def length = element.length - } - object AbstractTypeTest2 extends App { - def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] = - new SeqBuffer[Int, List[Int]] { - val element = List(e1, e2) - } - val buf = newIntSeqBuf(7, 8) - println("length = " + buf.length) - println("content = " + buf.element) - } +```scala mdoc:reset +abstract class Buffer[+T] { + val element: T +} +abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] { + def length = element.length +} +def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] = + new SeqBuffer[Int, List[Int]] { + val element = List(e1, e2) + } +val buf = newIntSeqBuf(7, 8) +println("length = " + buf.length) +println("content = " + buf.element) +``` Nótese que es necesario usar [variance annotations](variances.html) aquí; de otra manera no sería posible ocultar el tipo implementado por la secuencia concreta del objeto retornado por `newIntSeqBuf`. Además, existen casos en los cuales no es posible remplazar tipos abstractos con tipos parametrizados. diff --git a/_es/tour/basics.md b/_es/tour/basics.md index 998ddbe544..ba3519ef02 100644 --- a/_es/tour/basics.md +++ b/_es/tour/basics.md @@ -27,14 +27,14 @@ Muchos ejemplos de código en esta documentación están integrados con ScalaFid Las expresiones son sentencias computables. -```tut +```scala mdoc 1 + 1 ``` Se puede ver el resultado de evaluar expresiones usando `println`. {% scalafiddle %} -```tut +```scala mdoc println(1) // 1 println(1 + 1) // 2 println("Hello!") // Hello! @@ -46,7 +46,7 @@ println("Hello," + " world!") // Hello, world! Se puede dar un nombre al resultado de una expresión usando la palabra reservada `val`. -```tut +```scala mdoc val x = 1 + 1 println(x) // 2 ``` @@ -55,13 +55,13 @@ Los resultados con nombre, como `x` en el ejemplo, son llamados valores. Referen Los valores no pueden ser reasignados. -```tut:fail +```scala mdoc:fail x = 3 // This does not compile. ``` Scala es capaz de inferir el tipo de un valor. Aun así, también se puede indicar el tipo usando una anotación: -```tut +```scala mdoc:nest val x: Int = 1 + 1 ``` @@ -71,7 +71,7 @@ Nótese que la anotación del tipo `Int` sigue al identificador `x` de la variab Una variable es como un valor, excepto que a una variable se le puede re-asignar un valor después de declararla. Una variable se declara con la palabra reservada `var`. -```tut +```scala mdoc:nest var x = 1 + 1 x = 3 // This compiles because "x" is declared with the "var" keyword. println(x * x) // 9 @@ -79,7 +79,7 @@ println(x * x) // 9 Como con los valores, si se quiere se puede especificar el tipo de una variable mutable: -```tut +```scala mdoc:nest var x: Int = 1 + 1 ``` @@ -89,7 +89,7 @@ Se pueden combinar expresiones rodeándolas con `{}` . A esto le llamamos un blo El resultado de la última expresión del bloque es también el resultado total del bloque. -```tut +```scala mdoc println({ val x = 1 + 1 x + 1 @@ -102,7 +102,7 @@ Una función es una expresión que acepta parámetros. Una función se puede declarar anónima, sin nombre. Por ejemplo, ésta es una función que acepta un número entero `x`, y devuelve el resultado de incrementarlo: -```tut +```scala mdoc (x: Int) => x + 1 ``` @@ -111,7 +111,7 @@ La lista de parámetros de la función está a la izquierda de la flecha `=>`, y También podemos asignarle un nombre a la función. {% scalafiddle %} -```tut +```scala mdoc val addOne = (x: Int) => x + 1 println(addOne(1)) // 2 ``` @@ -120,7 +120,7 @@ println(addOne(1)) // 2 Las funciones pueden tomar varios parámetros. {% scalafiddle %} -```tut +```scala mdoc val add = (x: Int, y: Int) => x + y println(add(1, 2)) // 3 ``` @@ -128,7 +128,7 @@ println(add(1, 2)) // 3 O ninguno. -```tut +```scala mdoc val getTheAnswer = () => 42 println(getTheAnswer()) // 42 ``` @@ -140,7 +140,7 @@ Los métodos se parecen y comportan casi como a las funciones, pero se diferenci Un método se define con la palabra reservada `def`, seguida por el nombre del método, la lista de parámetros, el tipo de valores que el método devuelve, y el cuerpo del método. {% scalafiddle %} -```tut +```scala mdoc:nest def add(x: Int, y: Int): Int = x + y println(add(1, 2)) // 3 ``` @@ -151,7 +151,7 @@ Observe que el tipo de retorno se declara _después_ de la lista de parámetros, Un método puede tener varias listas de parámetros. {% scalafiddle %} -```tut +```scala mdoc def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier println(addThenMultiply(1, 2)(3)) // 9 ``` @@ -159,7 +159,7 @@ println(addThenMultiply(1, 2)(3)) // 9 O ninguna lista de parámetros. -```tut +```scala mdoc def name: String = System.getProperty("user.name") println("Hello, " + name + "!") ``` @@ -169,7 +169,7 @@ Hay otras diferencias, pero para simplificar, podemos pensar que son similares a Los métodos también pueden tener expresiones de varias lineas. {% scalafiddle %} -```tut +```scala mdoc def getSquareString(input: Double): String = { val square = input * input square.toString @@ -185,7 +185,7 @@ La ultima expresión en el cuerpo del método es el valor de retorno del mismo. Una clase se define con la palabra reservada `class`, seguida del nombre, y la lista de parámetros del constructor. -```tut +```scala mdoc class Greeter(prefix: String, suffix: String) { def greet(name: String): Unit = println(prefix + name + suffix) @@ -196,7 +196,7 @@ El método `greet` tiene un tipo de retorno `Unit`, que indica que el método no Se puede crear una instancia de una clase con la palabra reservada *new*. -```tut +```scala mdoc val greeter = new Greeter("Hello, ", "!") greeter.greet("Scala developer") // Hello, Scala developer! ``` @@ -208,13 +208,13 @@ Las clases se tratan en profundidad [más adelante](classes.html). Hay un tipo especial de clases en Scala, las llamadas "case" classes. Por defecto, las instancias de una case class son inmutables, y se comparan con otras solo por los valores que contienen en cada campo. Una case class se define con las palabras reservadas `case class`: -```tut +```scala mdoc case class Point(x: Int, y: Int) ``` Se puede crear una instancia de una `case class`, sin usar la palabra reservada `new`. -```tut +```scala mdoc val point = Point(1, 2) val anotherPoint = Point(1, 2) val yetAnotherPoint = Point(2, 2) @@ -222,7 +222,7 @@ val yetAnotherPoint = Point(2, 2) Y son comparadas por valor. -```tut +```scala mdoc if (point == anotherPoint) { println(point + " and " + anotherPoint + " are the same.") } else { @@ -244,7 +244,7 @@ Los objetos son instancias de una sola clase de su propia definición. Puedes pe Un objeto se define usando la palabra reservada `object`. -```tut +```scala mdoc object IdFactory { private var counter = 0 def create(): Int = { @@ -256,7 +256,7 @@ object IdFactory { Para acceder al objeto, lo referencias por su nombre. -```tut +```scala mdoc val newId: Int = IdFactory.create() println(newId) // 1 val newerId: Int = IdFactory.create() @@ -271,7 +271,7 @@ Los traits son tipos que contienen campos y métodos. Se pueden combinar múltip Un trait se define usando la palabra reservada `trait`. -```tut +```scala mdoc:nest trait Greeter { def greet(name: String): Unit } @@ -280,7 +280,7 @@ trait Greeter { Un `trait` también puede definir un método, o un valor, con una implementación por defecto. {% scalafiddle %} -```tut +```scala mdoc:reset trait Greeter { def greet(name: String): Unit = println("Hello, " + name + "!") @@ -289,7 +289,7 @@ trait Greeter { Un `trait` también puede extender otros traits, usando la palabra clave `extends`. Asimismo, en un `trait` se puede redefinir la implementación de un método heredado, usando la palabra reservada `override`. -```tut +```scala mdoc class DefaultGreeter extends Greeter class CustomizableGreeter(prefix: String, postfix: String) extends Greeter { @@ -316,7 +316,7 @@ El método principal (main) es el punto donde comienza la ejecución de un progr Usando un objeto, puedes definir el método principal de la siguiente forma: -```tut +```scala mdoc object Main { def main(args: Array[String]): Unit = println("Hello, Scala developer!") diff --git a/_es/tour/multiple-parameter-lists.md b/_es/tour/multiple-parameter-lists.md index 79d2318e3e..9ed0531042 100644 --- a/_es/tour/multiple-parameter-lists.md +++ b/_es/tour/multiple-parameter-lists.md @@ -18,7 +18,7 @@ Los métodos pueden definir múltiples listas de parámetros. Cuando un método A continuación hay un ejemplo, tal y como se define en el trait `TraversableOnce` en el API de colecciones de Scala: -``` +```scala mdoc:fail def foldLeft[B](z: B)(op: (B, A) => B): B ``` @@ -27,7 +27,7 @@ def foldLeft[B](z: B)(op: (B, A) => B): B Comenzando con un valor inicial 0, `foldLeft` aplica la función `(m, n) => m + n` a cada uno de los elementos de la lista y al valor acumulado previo. {% scalafiddle %} -```tut +```scala mdoc val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val res = numbers.foldLeft(0)((m, n) => m + n) println(res) // 55 @@ -38,7 +38,7 @@ println(res) // 55 A continuación se muestra otro ejemplo: {% scalafiddle %} -```tut +```scala mdoc object CurryTest extends App { def filter(xs: List[Int], p: Int => Boolean): List[Int] = @@ -59,9 +59,10 @@ _Nota: el método `modN` está parcialmente aplicado en las dos llamadas a `filt Aquí se muestra la salida del programa anterior: - List(2,4,6,8) - List(3,6) - +```scala mdoc +List(2,4,6,8) +List(3,6) +``` ### Casos de uso @@ -72,19 +73,19 @@ Casos de uso sugeridos para múltiples listas de parámetros incluyen: En Scala, la inferencia de tipos se realiza parámetro a parámetro. Suponer que se dispone del siguiente método: -```tut +```scala mdoc def foldLeft1[A, B](as: List[A], b0: B, op: (B, A) => B) = ??? ``` Si se invoca de la siguiente manera, se puede comprobar que no compila correctamente: -```tut:fail +```scala mdoc:fail def notPossible = foldLeft1(numbers, 0, _ + _) ``` Debes invocarlo de alguna de las maneras propuestas a continuación: -```tut +```scala mdoc def firstWay = foldLeft1[Int, Int](numbers, 0, _ + _) def secondWay = foldLeft1(numbers, 0, (a: Int, b: Int) => a + b) ``` @@ -93,7 +94,7 @@ Esto se debe a que Scala no será capaz de inferir el tipo de la función `_ + _ Moviéndo el parámetro `op` a su propia lista de parámetros, los tipos de `A` y `B` son inferidos en la primera lista de parámetros. Una vez se han inferido sus tipos, estos están disponibles para la segunda lista de parámetros y `_ + _ ` podrá casar con los tipos inferidos `(Int, Int) => Int` -```tut +```scala mdoc def foldLeft2[A, B](as: List[A], b0: B)(op: (B, A) => B) = ??? def possible = foldLeft2(numbers, 0)(_ + _) ``` @@ -107,7 +108,7 @@ Para especificar solamente ciertos parámetros como [`implicit`](https://docs.sc Un ejemplo de esto se muestra a continuación: -``` +```scala mdoc def execute(arg: Int)(implicit ec: scala.concurrent.ExecutionContext) = ??? ``` @@ -117,7 +118,7 @@ Cuando un método es invocado con menos parámetros que los que están declarado Por ejemplo, -```tut +```scala mdoc:nest val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val numberFunc = numbers.foldLeft(List[Int]()) _ diff --git a/_es/tour/tuples.md b/_es/tour/tuples.md index 004b06beac..27ba0d9819 100644 --- a/_es/tour/tuples.md +++ b/_es/tour/tuples.md @@ -18,7 +18,7 @@ un método. Una tupla con dos elementos puede ser creada del siguiente modo: -```tut +```scala mdoc val ingredient = ("Sugar", 25) ``` @@ -37,7 +37,7 @@ Cada clase tiene tantos parámetros como número de elementos. Una forma de acceder a los elementos de una tupla es por posición. Los elementos concretos se llaman `_1`, `_2`, y así sucesivamente. -```tut +```scala mdoc println(ingredient._1) // Sugar println(ingredient._2) // 25 ``` @@ -46,7 +46,7 @@ println(ingredient._2) // 25 Una tupla también puede ser dividida/expandida usando reconocimiento de patrones (pattern matching): -```tut +```scala mdoc val (name, quantity) = ingredient println(name) // Sugar println(quantity) // 25 @@ -57,7 +57,7 @@ En esta ocasión el tipo de `name` es inferido como `String` y el de A continuación otro ejemplo de reconocimiento de patrones con tuplas: -```tut +```scala mdoc val planets = List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6), ("Mars", 227.9), ("Jupiter", 778.3)) @@ -70,7 +70,7 @@ planets.foreach{ O en compresión de bucles `for`: -```tut +```scala mdoc val numPairs = List((2, 5), (3, -7), (20, 56)) for ((a, b) <- numPairs) { println(a * b) diff --git a/_es/tour/variances.md b/_es/tour/variances.md index feedee8fbb..eb961061a8 100644 --- a/_es/tour/variances.md +++ b/_es/tour/variances.md @@ -14,7 +14,7 @@ Scala soporta anotaciones de varianza para parámetros de tipo para [clases gen En el artículo sobre clases genéricas dimos un ejemplo de una pila mutable. Explicamos que el tipo definido por la clase `Stack[T]` es objeto de subtipos invariantes con respecto al parámetro de tipo. Esto puede restringir el reuso de la abstracción (la clase). Ahora derivaremos una implementación funcional (es decir, inmutable) para pilas que no tienen esta restricción. Nótese que este es un ejemplo avanzado que combina el uso de [métodos polimórficos](polymorphic-methods.html), [límites de tipado inferiores](lower-type-bounds.html), y anotaciones de parámetros de tipo covariante de una forma no trivial. Además hacemos uso de [clases internas](inner-classes.html) para encadenar los elementos de la pila sin enlaces explícitos. -```tut +```scala mdoc class Stack[+T] { def push[S >: T](elem: S): Stack[S] = new Stack[S] { override def top: S = elem diff --git a/_fr/tour/basics.md b/_fr/tour/basics.md index d30be44941..a16e3c7970 100644 --- a/_fr/tour/basics.md +++ b/_fr/tour/basics.md @@ -8,4 +8,4 @@ language: fr next-page: unified-types previous-page: tour-of-scala ---- \ No newline at end of file +--- diff --git a/_fr/tour/classes.md b/_fr/tour/classes.md index 63480c2848..40f56d0513 100644 --- a/_fr/tour/classes.md +++ b/_fr/tour/classes.md @@ -9,4 +9,4 @@ language: fr next-page: traits previous-page: unified-types ---- \ No newline at end of file +--- diff --git a/_fr/tour/package-objects.md b/_fr/tour/package-objects.md index 9c1b78716d..80cfb5e055 100644 --- a/_fr/tour/package-objects.md +++ b/_fr/tour/package-objects.md @@ -6,4 +6,4 @@ partof: scala-tour num: 36 previous-page: packages-and-imports ---- \ No newline at end of file +--- diff --git a/_fr/tour/traits.md b/_fr/tour/traits.md index fb57d520aa..069648bb53 100644 --- a/_fr/tour/traits.md +++ b/_fr/tour/traits.md @@ -9,4 +9,4 @@ language: fr next-page: tuples previous-page: classes ---- \ No newline at end of file +--- diff --git a/_fr/tour/tuples.md b/_fr/tour/tuples.md index 74cd02ff85..c4c268f376 100644 --- a/_fr/tour/tuples.md +++ b/_fr/tour/tuples.md @@ -9,4 +9,4 @@ language: fr next-page: mixin-class-composition previous-page: traits ---- \ No newline at end of file +--- diff --git a/_fr/tour/unified-types.md b/_fr/tour/unified-types.md index d914ee3fd0..6ecf013319 100644 --- a/_fr/tour/unified-types.md +++ b/_fr/tour/unified-types.md @@ -9,4 +9,4 @@ language: fr next-page: classes previous-page: basics ---- \ No newline at end of file +--- diff --git a/_ja/tour/abstract-type-members.md b/_ja/tour/abstract-type-members.md index 0a0a61f387..2f480833bf 100644 --- a/_ja/tour/abstract-type-members.md +++ b/_ja/tour/abstract-type-members.md @@ -18,7 +18,7 @@ prerequisite-knowledge: variance, upper-type-bound これは具体的な実装で実際の型を定義するという意味です。 こちらが例です。 -```tut +```scala mdoc trait Buffer { type T val element: T @@ -26,7 +26,7 @@ trait Buffer { ``` こちらでは、抽象型`type T`を定義しています。それは`element`の型を記述するために使われます。このトレイトを抽象クラスで継承し、より具体的にするために上限型境界を`T`に追加することができます。 -```tut +```scala mdoc abstract class SeqBuffer extends Buffer { type U type T <: Seq[U] @@ -38,7 +38,7 @@ abstract class SeqBuffer extends Buffer { 抽象型メンバーを持つトレイトと[クラス](classes.html)は無名クラスのインスタンス化と組み合わせてよく使われます。 これを説明するために、今から整数のリストを参照するシーケンスバッファーを扱うプログラムを見てみます。 -```tut +```scala mdoc abstract class IntSeqBuffer extends SeqBuffer { type U = Int } @@ -57,7 +57,7 @@ println("content = " + buf.element) 抽象型メンバーをクラスの型パラメータに変えることも、その逆も可能です。以下は上記コードの型パラメータのみを使うバージョンです。 -```tut +```scala mdoc:nest abstract class Buffer[+T] { val element: T } diff --git a/_ja/tour/annotations.md b/_ja/tour/annotations.md index 7347894b70..d0fad2e82a 100644 --- a/_ja/tour/annotations.md +++ b/_ja/tour/annotations.md @@ -29,7 +29,7 @@ object DeprecationDemo extends App { ## エンコーディングの正確性を保証するアノテーション 条件が一致しない場合にコンパイルを失敗させるアノテーションもあります。例えば、アノテーション`@tailrec`はメソッドが[末尾再帰](https://en.wikipedia.org/wiki/Tail_call)であると保証します。末尾再帰ではメモリ使用量が一定になります。こちらは階乗を計算するメソッドの中での使われ方です。 -```tut +```scala mdoc import scala.annotation.tailrec def factorial(x: Int): Int = { diff --git a/_ja/tour/basics.md b/_ja/tour/basics.md index 669564483d..b2b06317bb 100644 --- a/_ja/tour/basics.md +++ b/_ja/tour/basics.md @@ -32,13 +32,13 @@ ScalaFiddleを利用することでブラウザ上でScalaを実行すること 式は計算可能な文です。 -``` +```scala mdoc 1 + 1 ``` `println`を使うことで、式の結果を出力できます。 {% scalafiddle %} -```tut +```scala mdoc println(1) // 1 println(1 + 1) // 2 println("Hello!") // Hello! @@ -50,7 +50,7 @@ println("Hello," + " world!") // Hello, world! `val`キーワードを利用することで、式の結果に名前を付けることができます。 -```tut +```scala mdoc val x = 1 + 1 println(x) // 2 ``` @@ -60,13 +60,13 @@ println(x) // 2 値は再代入することができません。 -```tut:fail +```scala mdoc:fail x = 3 // この記述はコンパイルされません。 ``` 値の型は推測可能ですが、このように型を明示的に宣言することもできます。 -```tut +```scala mdoc:nest val x: Int = 1 + 1 ``` @@ -77,7 +77,7 @@ val x: Int = 1 + 1 再代入ができることを除けば、変数は値と似ています。 `var`キーワードを使うことで、変数は定義できます。 -```tut +```scala mdoc:nest var x = 1 + 1 x = 3 // "x"は"var"キーワードで宣言されているので、これはコンパイルされます。 println(x * x) // 9 @@ -85,7 +85,7 @@ println(x * x) // 9 値と同様に、型を宣言したければ、明示的に型を宣言することができます。 -```tut +```scala mdoc:nest var x: Int = 1 + 1 ``` @@ -96,7 +96,7 @@ var x: Int = 1 + 1 ブロックの最後の式の結果はブロック全体の結果にもなります。 -```tut +```scala mdoc println({ val x = 1 + 1 x + 1 @@ -108,7 +108,7 @@ println({ 関数はパラメーターを受け取る式です。 ここでは与えられた数値に1を足す無名関数(すなわち名前が無い関数)を宣言しています。 -```tut +```scala mdoc (x: Int) => x + 1 ``` `=>` の左側はパラメーターのリストです。右側はパラメーターを含む式です。 @@ -116,7 +116,7 @@ println({ 関数には名前をつけることもできます。 {% scalafiddle %} -```tut +```scala mdoc val addOne = (x: Int) => x + 1 println(addOne(1)) // 2 ``` @@ -125,7 +125,7 @@ println(addOne(1)) // 2 関数は複数のパラメーターをとることもできます。 {% scalafiddle %} -```tut +```scala mdoc val add = (x: Int, y: Int) => x + y println(add(1, 2)) // 3 ``` @@ -133,7 +133,7 @@ println(add(1, 2)) // 3 またパラメーターを取らないこともありえます。 -```tut +```scala mdoc val getTheAnswer = () => 42 println(getTheAnswer()) // 42 ``` @@ -145,7 +145,7 @@ println(getTheAnswer()) // 42 メソッドは `def` キーワードで定義されます。 `def` の後ろには名前、パラメーターリスト、戻り値の型、処理の内容が続きます。 {% scalafiddle %} -```tut +```scala mdoc:nest def add(x: Int, y: Int): Int = x + y println(add(1, 2)) // 3 ``` @@ -156,7 +156,7 @@ println(add(1, 2)) // 3 メソッドは複数のパラメーターリストを受け取ることができます。 {% scalafiddle %} -```tut +```scala mdoc def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier println(addThenMultiply(1, 2)(3)) // 9 ``` @@ -164,7 +164,7 @@ println(addThenMultiply(1, 2)(3)) // 9 また、パラメーターリストを一切受け取らないこともあります。 -```tut +```scala mdoc def name: String = System.getProperty("user.name") println("Hello, " + name + "!") ``` @@ -173,7 +173,7 @@ println("Hello, " + name + "!") メソッドは複数行の式も持つことができます。 {% scalafiddle %} -```tut +```scala mdoc def getSquareString(input: Double): String = { val square = input * input square.toString @@ -188,7 +188,7 @@ println(getSquareString(2.5)) // 6.25 `class` キーワードとその後ろに名前、コンストラクタパラメーターを続けることで、クラスを定義することができます。 -```tut +```scala mdoc class Greeter(prefix: String, suffix: String) { def greet(name: String): Unit = println(prefix + name + suffix) @@ -200,7 +200,7 @@ class Greeter(prefix: String, suffix: String) { `new` キーワードを使うことで、クラスのインスタンスを生成することができます。 -```tut +```scala mdoc val greeter = new Greeter("Hello, ", "!") greeter.greet("Scala developer") // Hello, Scala developer! ``` @@ -212,12 +212,12 @@ greeter.greet("Scala developer") // Hello, Scala developer! Scalaには"ケース"クラスという特別な種類のクラスがあります。デフォルトでケースクラスは不変であり、値で比較されます。 `case class` キーワードを利用して、ケースクラスを定義できます。 -```tut +```scala mdoc case class Point(x: Int, y: Int) ``` ケースクラスは、`new` キーワードなしでインスタンス化できます。 -```tut +```scala mdoc val point = Point(1, 2) val anotherPoint = Point(1, 2) val yetAnotherPoint = Point(2, 2) @@ -225,7 +225,7 @@ val yetAnotherPoint = Point(2, 2) ケースクラスは値で比較されます。 -```tut +```scala mdoc if (point == anotherPoint) { println(point + " と " + anotherPoint + " は同じです。") } else { @@ -248,7 +248,7 @@ if (point == yetAnotherPoint) { `object`キーワードを利用してオブジェクトを定義することができます。 -```tut +```scala mdoc object IdFactory { private var counter = 0 def create(): Int = { @@ -260,7 +260,7 @@ object IdFactory { 名前を参照してオブジェクトにアクセスすることができます。 -```tut +```scala mdoc val newId: Int = IdFactory.create() println(newId) // 1 val newerId: Int = IdFactory.create() @@ -275,7 +275,7 @@ println(newerId) // 2 `trait`キーワードでトレイトを定義することができます。 -```tut +```scala mdoc:nest trait Greeter { def greet(name: String): Unit } @@ -284,7 +284,7 @@ trait Greeter { トレイトはデフォルトの実装を持つこともできます。 {% scalafiddle %} -```tut +```scala mdoc:reset trait Greeter { def greet(name: String): Unit = println("Hello, " + name + "!") @@ -293,7 +293,7 @@ trait Greeter { `extends`キーワードでトレイトを継承することも、`override` キーワードで実装をオーバーライドすることもできます。 -```tut +```scala mdoc class DefaultGreeter extends Greeter class CustomizableGreeter(prefix: String, postfix: String) extends Greeter { @@ -321,7 +321,7 @@ customGreeter.greet("Scala developer") // How are you, Scala developer? オブジェクトを使い、以下のようにメインメソッドを定義することができます。 -```tut +```scala mdoc object Main { def main(args: Array[String]): Unit = println("Hello, Scala developer!") diff --git a/_ja/tour/by-name-parameters.md b/_ja/tour/by-name-parameters.md index 411afa5957..c3494f5634 100644 --- a/_ja/tour/by-name-parameters.md +++ b/_ja/tour/by-name-parameters.md @@ -14,7 +14,7 @@ previous-page: operators --- *名前渡しのパラメータ*は使用された時に評価されます。それらは*値渡しパラメータ*とは対照的です。名前渡しのパラメータを作るには、単純に`=>`を型の前につけます。 -```tut +```scala mdoc def calculate(input: => Int) = input * 37 ``` @@ -22,7 +22,7 @@ def calculate(input: => Int) = input * 37 こちらはwhileループをどのように実装するかの例です。 -```tut +```scala mdoc def whileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { body diff --git a/_ja/tour/case-classes.md b/_ja/tour/case-classes.md index 5493a00790..65cce59c9b 100644 --- a/_ja/tour/case-classes.md +++ b/_ja/tour/case-classes.md @@ -21,7 +21,7 @@ prerequisite-knowledge: classes, basics, mutability ## ケースクラスの宣言 最小のケースクラスにはキーワード`case class`、識別子、パラメータリスト(空かもしれません)が必要です。 -```tut +```scala mdoc case class Book(isbn: String) val frankenstein = Book("978-0486282114") diff --git a/_ja/tour/classes.md b/_ja/tour/classes.md index 36cf3ec851..7fdaea722d 100644 --- a/_ja/tour/classes.md +++ b/_ja/tour/classes.md @@ -24,7 +24,7 @@ Scalaにおけるクラスはオブジェクトを作るための設計図です 最小のクラス定義は単純にキーワード`class`と識別子だけというものです。 クラス名は大文字から始まるべきです。 -```tut +```scala mdoc class User val user1 = new User @@ -34,7 +34,7 @@ val user1 = new User しかしながら、コンストラクターとクラス本体は頻繁に欲しくなるでしょう。 こちらは位置情報のクラス定義の例になります。 -```tut +```scala mdoc class Point(var x: Int, var y: Int) { def move(dx: Int, dy: Int): Unit = { @@ -62,7 +62,7 @@ println(point1) // prints (2, 3) コンストラクターは次のようにデフォルト値を与えると省略可能なパラメーターを持つことができます。 -```tut +```scala mdoc:reset class Point(var x: Int = 0, var y: Int = 0) val origin = new Point // x と y には共に0がセットされます。 @@ -72,7 +72,7 @@ println(point1.x) // 1 が出力されます。 このバージョンの`Point`クラスでは、`x` と `y` はデフォルト値0を持ち、引数が必須ではありません。 しかしながらコンストラクタは引数を左から右に読み込むため、もし`y`の値だけを渡したい場合は、パラメーターに名前をつける必要があります。 -``` +```scala mdoc:reset class Point(var x: Int = 0, var y: Int = 0) val point2 = new Point(y=2) println(point2.y) // 2 が出力されます。 @@ -84,7 +84,7 @@ println(point2.y) // 2 が出力されます。 メンバーはデフォルトではパブリックになります。 クラスの外から隠したい場合は`private`アクセス修飾詞を使いましょう。 -```tut +```scala mdoc:reset class Point { private var _x = 0 private var _y = 0 @@ -116,14 +116,15 @@ point1.y = 101 // 警告が出力されます。 プライマリコンストラクタの`val` と `var` を持つパラメーターはパブリックになります。 しかしながら`val` は不変となるため、以下のように記述することはできません。 -``` +```scala mdoc:fail class Point(val x: Int, val y: Int) val point = new Point(1, 2) point.x = 3 // <-- コンパイルされません。 ``` `val` や `var` が存在しないパラメーターはクラス内でだけで参照できるプライベートな値や変数となります。 -``` + +```scala mdoc:fail class Point(x: Int, y: Int) val point = new Point(1, 2) point.x // <-- コンパイルされません。 diff --git a/_ja/tour/compound-types.md b/_ja/tour/compound-types.md index 061a5dc331..60be4af3c3 100644 --- a/_ja/tour/compound-types.md +++ b/_ja/tour/compound-types.md @@ -17,7 +17,7 @@ Scalaでは、これは*複合型*を用いて表現できます。複合型と 2つのトレイト`Cloneable`と`Resetable`があるとしましょう。 -```tut +```scala mdoc trait Cloneable extends java.lang.Cloneable { override def clone(): Cloneable = { super.clone().asInstanceOf[Cloneable] diff --git a/_ja/tour/default-parameter-values.md b/_ja/tour/default-parameter-values.md index dde76cdeaf..1e03cebe50 100644 --- a/_ja/tour/default-parameter-values.md +++ b/_ja/tour/default-parameter-values.md @@ -16,7 +16,7 @@ prerequisite-knowledge: named-arguments, function syntax Scalaはパラメータのデフォルト値を与えることができ、呼び出す側はこれらのパラメータを省略できます。 -```tut +```scala mdoc def log(message: String, level: String = "INFO") = println(s"$level: $message") log("System starting") // prints INFO: System starting @@ -25,7 +25,7 @@ log("User not found", "WARNING") // prints WARNING: User not found パラメータ`level`はデフォルト値を持つので、省略可能です。最終行では、引数`"WARNING"`はデフォルト値`"INFO"`を上書きします。Javaで同じ効果を得るのに、省略可能なパラメータをもつメソッドを複数使ってメソッドのオーバーロードをしたようなものです。しかしながら呼び出す側が引数をひとつ省略すると、以降全ての引数は名前つきにする必要があります。 -```tut +```scala mdoc class Point(val x: Double = 0, val y: Double = 0) val point1 = new Point(y = 1) @@ -34,7 +34,7 @@ val point1 = new Point(y = 1) Scalaで定義したデフォルトパラメータはJavaのコードから呼び出される時はオプショナルではありません。 -```tut +```scala mdoc:reset // Point.scala class Point(val x: Double = 0, val y: Double = 0) ``` diff --git a/_ja/tour/extractor-objects.md b/_ja/tour/extractor-objects.md index d3af5a18e7..8b0cf87797 100644 --- a/_ja/tour/extractor-objects.md +++ b/_ja/tour/extractor-objects.md @@ -17,7 +17,7 @@ previous-page: regular-expression-patterns `apply`メソッドが引数を取り、オブジェクトを作るコンストラクタであるように、`unapply`は1つのオブジェクトを受け取り、引数を返そうとします。 これはパターンマッチングと部分関数で最も頻繁に使われます。 -```tut +```scala mdoc import scala.util.Random object CustomerID { @@ -43,19 +43,19 @@ customer1ID match { 値を定義する文で、パターン中に新しい変数を使うことができるので、抽出子は変数を初期化するのに使えます。この場合unapplyメソッドが初期値を与えます。 -```tut +```scala mdoc val customer2ID = CustomerID("Nico") val CustomerID(name) = customer2ID println(name) // prints Nico ``` これは `val name = CustomerID.unapply(customer2ID).get`.と同じです。 -```tut +```scala mdoc val CustomerID(name2) = "--asdfasdfasdf" ``` もし一致しない場合`scala.MatchError`が投げられます。 -```tut:fail +```scala mdoc:crash val CustomerID(name3) = "-asdfasdfasdf" ``` diff --git a/_ja/tour/for-comprehensions.md b/_ja/tour/for-comprehensions.md index eccd124c8c..c673135b2b 100644 --- a/_ja/tour/for-comprehensions.md +++ b/_ja/tour/for-comprehensions.md @@ -20,7 +20,7 @@ Scalaは*シーケンス内包表記*を表現するための軽量な記法を こちらは例です。 -```tut +```scala mdoc case class User(name: String, age: Int) val userBase = List(User("Travis", 28), @@ -40,7 +40,7 @@ twentySomethings.foreach(name => println(name)) // prints Travis Dennis こちらは2つのジェネレータを使ったより複雑な例です。 合計が与えられた値`v`と等しくなる、`0`から`n-1`の全てのペアを計算します。 -```tut +```scala mdoc def foo(n: Int, v: Int) = for (i <- 0 until n; j <- 0 until n if i + j == v) @@ -66,7 +66,7 @@ foo(10, 10) foreach { これは副作用をもたらす必要があるときに役立ちます。 こちらは先に出たプログラムと同等のものですが、`yield`を使っていません。 -```tut +```scala mdoc:nest def foo(n: Int, v: Int) = for (i <- 0 until n; j <- 0 until n if i + j == v) diff --git a/_ja/tour/generic-classes.md b/_ja/tour/generic-classes.md index 8e04bacd92..148ae5013c 100644 --- a/_ja/tour/generic-classes.md +++ b/_ja/tour/generic-classes.md @@ -18,7 +18,7 @@ assumed-knowledge: classes unified-types ## ジェネリッククラスの定義 ジェネリッククラスは角カッコ`[]`の中にパラメータとして型を1つ受け取ります。 型パラメータの識別子として文字`A`を使う習慣がありますが、任意のパラメータ名を使うことができます。 -```tut +```scala mdoc class Stack[A] { private var elements: List[A] = Nil def push(x: A) { elements = x :: elements } diff --git a/_ja/tour/higher-order-functions.md b/_ja/tour/higher-order-functions.md index 88d432aaf5..73305802ee 100644 --- a/_ja/tour/higher-order-functions.md +++ b/_ja/tour/higher-order-functions.md @@ -19,7 +19,7 @@ previous-page: mixin-class-composition ここでは"高階関数"というフレーズを関数をパラメーターとして受け取る、または関数を返すメソッドと関数の両方に対して使います。 もっとも一般的な例の1つは、Scalaのコレクションで利用可能な高階関数`map`です。 -```tut +```scala mdoc val salaries = Seq(20000, 70000, 40000) val doubleSalary = (x: Int) => x * 2 val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000) @@ -29,7 +29,7 @@ val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000) 3行目で、給与のリストのそれぞれの値に`doubleSalary`が適用されます。 コードを減らすため、以下のように無名関数を作ることができ、引数として直接mapに渡すことができます -``` +```scala mdoc:nest val salaries = Seq(20000, 70000, 40000) val newSalaries = salaries.map(x => x * 2) // List(40000, 140000, 80000) ``` @@ -37,7 +37,7 @@ val newSalaries = salaries.map(x => x * 2) // List(40000, 140000, 80000) それはmap関数が期待する型を基にコンパイラーが型を推論できるからです。 さらに言えば、慣用的には同じコードを以下のように書きます。 -```tut +```scala mdoc:nest val salaries = Seq(20000, 70000, 40000) val newSalaries = salaries.map(_ * 2) ``` @@ -46,7 +46,7 @@ Scalaコンパイラはパラメーターの型を(Intが1つだけと)既 ## メソッドを関数に強制変換 高階関数には引数としてとしてメソッドを渡すことも可能で、それはScalaコンパイラがメソッドを関数に強制変換するからです。 -``` +```scala mdoc case class WeeklyWeatherForecast(temperatures: Seq[Double]) { private def convertCtoF(temp: Double) = temp * 1.8 + 32 @@ -62,7 +62,7 @@ case class WeeklyWeatherForecast(temperatures: Seq[Double]) { たとえば、何通りかの係数で人の給料を上げるメソッドが欲しいとしましょう。 高階関数を作らないなら、こんな感じになるかもしれません。 -```tut +```scala mdoc object SalaryRaiser { def smallPromotion(salaries: List[Double]): List[Double] = @@ -79,7 +79,7 @@ object SalaryRaiser { 3つのメソッドはそれぞれ掛け算の係数のみ異なることに気をつけてください。 簡潔にするため、以下のように繰り返されているコードを高階関数に抽出することができます。 -```tut +```scala mdoc:nest object SalaryRaiser { private def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] = @@ -102,7 +102,7 @@ object SalaryRaiser { 関数を生成したい場合がいくつかあります。 こちらは関数を返すメソッドの例になります。 -```tut +```scala mdoc def urlBuilder(ssl: Boolean, domainName: String): (String, String) => String = { val schema = if (ssl) "https://" else "http://" (endpoint: String, query: String) => s"$schema$domainName/$endpoint?$query" diff --git a/_ja/tour/implicit-conversions.md b/_ja/tour/implicit-conversions.md index 107979e2dc..634dabcfca 100644 --- a/_ja/tour/implicit-conversions.md +++ b/_ja/tour/implicit-conversions.md @@ -30,7 +30,7 @@ List(1, 2, 3) <= List(4, 5) ``` implicitなメソッド`Int => Ordered[Int]`は`scala.Predef.intWrapper`を通じて自動的に提供されます。implicitなメソッドの例`List[A] => Ordered[List[A]]`は以下にあります。 -```tut +```scala mdoc import scala.language.implicitConversions implicit def list2ordered[A](x: List[A]) @@ -44,7 +44,7 @@ implicit def list2ordered[A](x: List[A]) 例えば、`java.lang.Integer`を受け取るようなJavaのメソッドを呼び出す時、自由に`scala.Int`を代わりに渡すことができます。それはPredefオブジェクトが以下の暗黙の変換をを含んでいるからです。 -```tut +```scala mdoc import scala.language.implicitConversions implicit def int2Integer(x: Int) = diff --git a/_ja/tour/implicit-parameters.md b/_ja/tour/implicit-parameters.md index 53613be8ee..30ff6028df 100644 --- a/_ja/tour/implicit-parameters.md +++ b/_ja/tour/implicit-parameters.md @@ -26,7 +26,7 @@ Scalaがimplicitをどこから見つけるかについてのより詳しいガ 以下の例では、モノイドの`add`と`unit`の演算を使い、要素のリストの合計を計算するメソッド`sum`を定義しています。 implicitの値をトップレベルには置けないことに注意してください。 -```tut +```scala mdoc abstract class Monoid[A] { def add(x: A, y: A): A def unit: A diff --git a/_ja/tour/inner-classes.md b/_ja/tour/inner-classes.md index 4745d445aa..5d38b1f1f6 100644 --- a/_ja/tour/inner-classes.md +++ b/_ja/tour/inner-classes.md @@ -20,7 +20,7 @@ Javaのような、内部クラスが外側のクラスのメンバーとなる その違いを示すために、グラフデータ型の実装をさっと書きます。 -```tut +```scala mdoc class Graph { class Node { var connectedNodes: List[Node] = Nil @@ -41,7 +41,7 @@ class Graph { このプログラムはグラフをノードのリスト(`List[Node]`)で表現しています。いずれのノードも接続している他のノードへのリスト(`connectedNodes`)を保持します。`class Node`は `class Graph`の中にネストしているので、 _パス依存型_ です。 そのため`connectedNodes`の中にある全てのノードは同じ`Graph`インスタンスから`newNode`を使用して作る必要があります。 -```tut +```scala mdoc val graph1: Graph = new Graph val node1: graph1.Node = graph1.newNode val node2: graph1.Node = graph1.newNode @@ -56,7 +56,7 @@ node3.connectTo(node1) それは別のグラフのノードは別の型を持つからです。 こちらは不正なプログラムです。 -``` +```scala mdoc:fail val graph1: Graph = new Graph val node1: graph1.Node = graph1.newNode val node2: graph1.Node = graph1.newNode @@ -70,7 +70,7 @@ node1.connectTo(node3) // illegal! Scalaではそのような型も同様に表現することができ、`Graph#Node`と書きます。 もし他のグラフのノードに接続できるようにしたければ、以下の方法で最初のグラフ実装の定義を変える必要があります。 -```tut +```scala mdoc:nest class Graph { class Node { var connectedNodes: List[Graph#Node] = Nil diff --git a/_ja/tour/lower-type-bounds.md b/_ja/tour/lower-type-bounds.md index e522216a76..62a15447d3 100644 --- a/_ja/tour/lower-type-bounds.md +++ b/_ja/tour/lower-type-bounds.md @@ -18,7 +18,7 @@ prerequisite-knowledge: upper-type-bounds, generics, variance 以下はこれが役立つ場合の例です。 -```tut:fail +```scala mdoc:fail trait Node[+B] { def prepend(elem: B): Node[B] } @@ -44,7 +44,7 @@ case class Nil[+B]() extends Node[B] { これを解決するためには、`prepend`のパラメータ`elem`の型の変位指定を逆転させる必要があります。 これを実現するには、下限型境界として`B`を持つ新しい型パラメータ`U`を導入します。 -```tut +```scala mdoc trait Node[+B] { def prepend[U >: B](elem: U): Node[U] } @@ -61,7 +61,7 @@ case class Nil[+B]() extends Node[B] { ``` すると、以下のようなことができます。 -```tut +```scala mdoc trait Bird case class AfricanSwallow() extends Bird case class EuropeanSwallow() extends Bird diff --git a/_ja/tour/mixin-class-composition.md b/_ja/tour/mixin-class-composition.md index c5d40ebe16..8b4e26067e 100644 --- a/_ja/tour/mixin-class-composition.md +++ b/_ja/tour/mixin-class-composition.md @@ -15,7 +15,7 @@ prerequisite-knowledge: inheritance, traits, abstract-classes, unified-types --- ミックスインはクラスを構成するのに使われるトレイトです。 -```tut +```scala mdoc abstract class A { val message: String } @@ -37,7 +37,7 @@ println(d.loudMessage) // I'M AN INSTANCE OF CLASS B それでは抽象クラスから始まる興味深い例を見てみましょう。 -```tut +```scala mdoc abstract class AbsIterator { type T def hasNext: Boolean @@ -47,7 +47,7 @@ abstract class AbsIterator { クラスは抽象型`T`と標準的なイテレーターのメソッドを持ちます。 次に、(全ての抽象メンバー`T`, `hasNext`, `next`が実装を持つ)具象クラスを実装します。 -```tut +```scala mdoc class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 @@ -64,7 +64,7 @@ class StringIterator(s: String) extends AbsIterator { それでは`AbsIterator`を継承したトレイトも作ってみましょう。 -```tut +```scala mdoc trait RichIterator extends AbsIterator { def foreach(f: T => Unit): Unit = while (hasNext) f(next()) } @@ -73,7 +73,7 @@ trait RichIterator extends AbsIterator { `RichIterator`はトレイトなので、`RichIterator`はAbsIteratorの抽象メンバーを実装する必要がありません。 `StringIterator`と`RichIterator`の機能を1つのクラスに組み合わせてみましょう。 -```tut +```scala mdoc class RichStringIter extends StringIterator("Scala") with RichIterator val richStringIter = new RichStringIter richStringIter foreach println diff --git a/_ja/tour/multiple-parameter-lists.md b/_ja/tour/multiple-parameter-lists.md index 3cddffe859..ff267531b8 100644 --- a/_ja/tour/multiple-parameter-lists.md +++ b/_ja/tour/multiple-parameter-lists.md @@ -19,7 +19,7 @@ previous-page: nested-functions こちらはScalaのコレクションAPIの `TraversableOnce`トレイトで定義されている実例です。 -``` +```scala mdoc:fail def foldLeft[B](z: B)(op: (B, A) => B): B ``` `foldLeft`は、2つのパラメータを取る関数`op`を、初期値`z`とこのコレクションの全要素に対して左から右に適用していきます。 @@ -28,7 +28,7 @@ def foldLeft[B](z: B)(op: (B, A) => B): B 初期値0から始まり、`foldLeft`はここではリスト内の各要素とその一つ前の累積値に関数`(m, n) => m + n`を適用します。 {% scalafiddle %} -```tut +```scala mdoc val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val res = numbers.foldLeft(0)((m, n) => m + n) println(res) // 55 @@ -43,13 +43,13 @@ println(res) // 55 複数パラメータリストがない場合、このコードは以下のようになります。 -``` +```scala mdoc:fail numbers.foldLeft(0, (m: Int, n: Int) => m + n) ``` 複数パラメータリストを使うことで、Scalaの型インターフェースの利点を享受でき、以下のようにコードをより簡潔にすることができるのです。 -``` +```scala mdoc numbers.foldLeft(0)(_ + _) ``` 単一のパラメータリストではScalaコンパイラが関数のパラメータを型推論できないので、このようなことはできません。 @@ -58,7 +58,7 @@ numbers.foldLeft(0)(_ + _) 特定のパラメータだけを`implicit`として指定するには、`implicit`のパラメーターリストに入れなければなりません。 こちらが例です。 -``` +```scala mdoc def execute(arg: Int)(implicit ec: scala.concurrent.ExecutionContext) = ??? ``` @@ -68,7 +68,7 @@ def execute(arg: Int)(implicit ec: scala.concurrent.ExecutionContext) = ??? これは一般的に[部分適用](https://en.wikipedia.org/wiki/Partial_application)として知られています。 例えば -```tut +```scala mdoc:nest val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val numberFunc = numbers.foldLeft(List[Int]()) _ val squares = numberFunc((xs, x) => xs :+ x*x) diff --git a/_ja/tour/named-arguments.md b/_ja/tour/named-arguments.md index eda94a0c8c..8ce70335a9 100644 --- a/_ja/tour/named-arguments.md +++ b/_ja/tour/named-arguments.md @@ -16,7 +16,7 @@ prerequisite-knowledge: function-syntax メソッドを呼ぶ時、以下のように引数にパラメータ名でラベル付が可能です。 -```tut +```scala mdoc def printName(first: String, last: String): Unit = { println(first + " " + last) } @@ -28,7 +28,7 @@ printName(last = "Smith", first = "John") // Prints "John Smith" 名前付き引数の順序はどのように並び替えられるかに気をつけましょう。ただし、名前つき引数と名前つきでない引数がある場合は、名前つきでない引数は引数リストの最初に置かれ、かつメソッドシグネチャのパラメーター順でなければなりません。 -```tut:fail +```scala mdoc:fail printName(last = "Smith", "john") // error: positional after named argument ``` diff --git a/_ja/tour/nested-functions.md b/_ja/tour/nested-functions.md index 2769c20674..9701e421cc 100644 --- a/_ja/tour/nested-functions.md +++ b/_ja/tour/nested-functions.md @@ -17,7 +17,7 @@ Scalaではメソッドの定義をネストする(_訳注:入れ子にす 以下のコードは与えられた数値の階乗を計算するための`factorial`メソッドを提供します。 {% scalafiddle %} -```tut +```scala mdoc def factorial(x: Int): Int = { def fact(x: Int, accumulator: Int): Int = { if (x <= 1) accumulator diff --git a/_ja/tour/operators.md b/_ja/tour/operators.md index f5b1ac6ed5..0b13e639bd 100644 --- a/_ja/tour/operators.md +++ b/_ja/tour/operators.md @@ -28,7 +28,7 @@ Scalaでは演算子はメソッドです。パラメータを1つだけ持つ ## 演算子の定義方法と使い方 有効な識別子であれば演算子として使用できます。これは `add`のような名前も`+`のような記号も含みます。 -```tut +```scala mdoc case class Vec(x: Double, y: Double) { def +(that: Vec) = Vec(this.x + that.x, this.y + that.y) } @@ -43,7 +43,7 @@ vector3.y // 3.0 クラスVecはメソッド`+`を持ち、 `vector1`と`vector2`を足しわせるのに使います。丸括弧を用いて、複雑な式を読みやすい構文で作ることができます。 こちらはクラス`MyBool`の定義です。クラス`MyBool`はメソッド`and`と`or`を含みます。 -```tut +```scala mdoc case class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that @@ -53,7 +53,7 @@ case class MyBool(x: Boolean) { この時、`and`と`or`を中置演算子として使えます。 -```tut +```scala mdoc def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) ``` diff --git a/_ja/tour/packages-and-imports.md b/_ja/tour/packages-and-imports.md index dd2e42f844..8e44239b05 100644 --- a/_ja/tour/packages-and-imports.md +++ b/_ja/tour/packages-and-imports.md @@ -70,7 +70,7 @@ import users.{UserPreferences => UPrefs} // インポートし利便性のた ``` ScalaのJavaと異なる点の1つはインポートがどこでも使える点です。 -```tut +```scala mdoc def sqrtplus1(x: Int) = { import scala.math.sqrt sqrt(x) + 1.0 diff --git a/_ja/tour/pattern-matching.md b/_ja/tour/pattern-matching.md index f5d506bdf4..9e1f5d9692 100644 --- a/_ja/tour/pattern-matching.md +++ b/_ja/tour/pattern-matching.md @@ -22,7 +22,7 @@ Javaの`switch`文の強化バージョンで、if/else文の連続の代わり ## 構文 マッチ式は値、キーワード`match`と少なくとも1つの`case`句を持ちます。 -```tut +```scala mdoc import scala.util.Random val x: Int = Random.nextInt(10) @@ -39,7 +39,7 @@ x match { ケースは*オルタナティブ*とも呼ばれます。 マッチ式は値を持ちます。 -```tut +```scala mdoc def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" @@ -55,7 +55,7 @@ matchTest(1) // one ケースクラスはパターンマッチングで特に役立ちます。 -```tut +```scala mdoc abstract class Notification case class Email(sender: String, title: String, body: String) extends Notification @@ -124,7 +124,7 @@ println(showImportantNotification(importantSms, importantPeopleInfo)) ## 型のみでのマッチング 以下のように型のみでマッチすることができます。 -```tut +```scala mdoc abstract class Device case class Phone(model: String) extends Device { def screenOff = "Turning screen off" @@ -146,7 +146,7 @@ def goIdle(device: Device) = device match { トレイトとクラスに`sealed`をつけると、全てのサブタイプは同一ファイル内で宣言されなければならないという意味になります。 これは全てのサブタイプが既知であることを保証します。 -```tut +```scala mdoc sealed abstract class Furniture case class Couch() extends Furniture case class Chair() extends Furniture diff --git a/_ja/tour/polymorphic-methods.md b/_ja/tour/polymorphic-methods.md index 7eac75ff39..6143ef2612 100644 --- a/_ja/tour/polymorphic-methods.md +++ b/_ja/tour/polymorphic-methods.md @@ -20,7 +20,7 @@ Scalaのメソッドは値と同様に型によってパラメータ化するこ こちらが例です。 -```tut +```scala mdoc def listOfDuplicates[A](x: A, length: Int): List[A] = { if (length < 1) Nil diff --git a/_ja/tour/regular-expression-patterns.md b/_ja/tour/regular-expression-patterns.md index a81168544c..05882529c0 100644 --- a/_ja/tour/regular-expression-patterns.md +++ b/_ja/tour/regular-expression-patterns.md @@ -16,7 +16,7 @@ previous-page: singleton-objects 正規表現はデータの中からパターン(またはその欠如)を探すために使うことができる文字列です。 どんな文字列も`.r`メソッドを使うことで、正規表現に変換できます。 -```tut +```scala mdoc import scala.util.matching.Regex val numberPattern: Regex = "[0-9]".r @@ -30,7 +30,7 @@ numberPattern.findFirstMatchIn("awesomepassword") match { 括弧を使うことで、正規表現のグループを探すこともできます。 -```tut +```scala mdoc import scala.util.matching.Regex val keyValPattern: Regex = "([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r diff --git a/_ja/tour/self-types.md b/_ja/tour/self-types.md index 1bffbfe63c..103fa0d2c2 100644 --- a/_ja/tour/self-types.md +++ b/_ja/tour/self-types.md @@ -21,7 +21,7 @@ prerequisite-knowledge: nested-classes, mixin-class-composition その構文は普通の関数構文のように見えますが、全く異なる意味があります。 トレイトで自分型を使うには、識別子、ミックスインする他のトレイトの型、`=>`を書きます(例えば `someIdentifier: SomeOtherTrait =>`)。 -```tut +```scala mdoc trait User { def username: String } diff --git a/_ja/tour/singleton-objects.md b/_ja/tour/singleton-objects.md index 5681d92552..69ce1aeede 100644 --- a/_ja/tour/singleton-objects.md +++ b/_ja/tour/singleton-objects.md @@ -21,7 +21,7 @@ prerequisite-knowledge: classes, methods, private-methods, packages, option # シングルトンオブジェクトの定義 オブジェクトは値です。オブジェクトの定義はクラスのように見えますが、キーワード`object`を使います。 -```tut +```scala mdoc object Box ``` これはメソッドを持つオブジェクトの例です。 @@ -84,7 +84,7 @@ circle1.area `class Circle`は各インスタンスの固有のメンバー`area`を持ち、シングルトンオブジェクト`object Circle`は全てのインスタンスで利用できる`calculateArea`メソッドを持ちます。 コンパニオンオブジェクトはファクトリーメソッドを含むことができます。 -```tut +```scala mdoc class Email(val username: String, val domainName: String) object Email { diff --git a/_ja/tour/traits.md b/_ja/tour/traits.md index 5152af0fb0..887eed1741 100644 --- a/_ja/tour/traits.md +++ b/_ja/tour/traits.md @@ -21,12 +21,12 @@ prerequisite-knowledge: expressions, classes, generics, objects, companion-objec ## トレイトを定義する 最小のトレイトはキーワード `trait` と識別子だけというものです。 -```tut +```scala mdoc trait HairColor ``` トレイトはジェネリック型として、抽象メソッドとあわせて使うと特に便利です。 -```tut +```scala mdoc trait Iterator[A] { def hasNext: Boolean def next(): A @@ -37,7 +37,7 @@ trait Iterator[A] { ## トレイトの使い方 トレイトを継承するには `extends` キーワードを使います。その際に、 `override` キーワードを利用しすべての抽象メンバーを実装します。 -```tut +```scala mdoc:nest trait Iterator[A] { def hasNext: Boolean def next(): A @@ -66,7 +66,7 @@ iterator.next() // returns 1 ## サブタイピング あるトレイトが必要とされている場所に、代りにそのトレイトのサブタイプを使うことができます。 -```tut +```scala mdoc import scala.collection.mutable.ArrayBuffer trait Pet { diff --git a/_ja/tour/tuples.md b/_ja/tour/tuples.md index 822a6f5a72..7729138914 100644 --- a/_ja/tour/tuples.md +++ b/_ja/tour/tuples.md @@ -21,7 +21,7 @@ Scalaではタプルは決まった数の要素を含む値であり、各要素 2つの要素を持つタプルは以下のように作ることができます。 -```tut +```scala mdoc val ingredient = ("Sugar" , 25) ``` ここでは`String`要素を1つと`Int`要素を1つ含むタプルを作っています。 @@ -36,14 +36,14 @@ val ingredient = ("Sugar" , 25) タプルの要素へのアクセス方法の1つとして、位置があります。 個々の要素は`_1`、`_2`などと名付けられます。 -```tut +```scala mdoc println(ingredient._1) // Sugar println(ingredient._2) // 25 ``` ## タプルでのパターンマッチング タプルはパターンマッチングを使って分解することもできます。 -```tut +```scala mdoc val (name, quantity) = ingredient println(name) // Sugar println(quantity) // 25 @@ -53,7 +53,7 @@ println(quantity) // 25 こちらはタプルのパターンマッチングの他の例です。 -```tut +```scala mdoc val planets = List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6), ("Mars", 227.9), ("Jupiter", 778.3)) @@ -66,7 +66,7 @@ planets.foreach{ また、`for`内包表記では以下のようになります。 -```tut +```scala mdoc val numPairs = List((2, 5), (3, -7), (20, 56)) for ((a, b) <- numPairs) { println(a * b) diff --git a/_ja/tour/type-inference.md b/_ja/tour/type-inference.md index 3fb93ee339..4fafc6814f 100644 --- a/_ja/tour/type-inference.md +++ b/_ja/tour/type-inference.md @@ -16,19 +16,19 @@ Scalaコンパイラが式の型を推論できることが多いので、明示 ## 型の省略 -```tut +```scala mdoc val businessName = "Montreux Jazz Café" ``` コンパイラは`businessName`がStringだと検知できます。これはメソッドでも同様に動きます。 -```tut +```scala mdoc def squareOf(x: Int) = x * x ``` コンパイラは戻り値の型が`Int`だと推論できるので、明示的な戻り値の型は必要ありません。 再帰的メソッドでは、コンパイラは結果の型を推論できません。こちらはこの理由でコンパイラが失敗するプログラムです。 -```tut:fail +```scala mdoc:fail def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) ``` @@ -36,7 +36,7 @@ def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) こちらは2つの例です。 -```tut +```scala mdoc case class MyPair[A, B](x: A, y: B) val p = MyPair(1, "scala") // 型: MyPair[Int, String] @@ -49,7 +49,7 @@ val q = id(1) // 型: Int コンパイラはメソッドのパラメータ型を決して推論しません。しかし、関数が引数として渡されている場合は、無名関数のパラメータ型を推論できます。 -```tut +```scala mdoc Seq(1, 3, 4).map(x => x * 2) // List(2, 6, 8) ``` @@ -61,13 +61,13 @@ mapのパラメータは`f: A => B`です。`Seq`の中に整数が入ってい また、型推論は特定の型を推論することがあります。次のように書いたとします。 -```tut +```scala var obj = null ``` これ以上進められず、再割り当てができません。 -```tut:fail +```scala mdoc:fail obj = new AnyRef ``` diff --git a/_ja/tour/unified-types.md b/_ja/tour/unified-types.md index 7e5b4841d4..8f9710b62a 100644 --- a/_ja/tour/unified-types.md +++ b/_ja/tour/unified-types.md @@ -35,7 +35,7 @@ null非許容です。 以下にstring、integer、character、boolean、関数が他のオブジェクトと同様に全てオブジェクトであるという例を示します。 -```tut +```scala mdoc val list: List[Any] = List( "a string", 732, // integer @@ -67,7 +67,7 @@ true 例えば、 -```tut +```scala mdoc val x: Long = 987654321 val y: Float = x // 9.8765434E8 (この場合精度が落ちることに注意してください) diff --git a/_ja/tour/upper-type-bounds.md b/_ja/tour/upper-type-bounds.md index ac6b1f2440..7d8ac4df9a 100644 --- a/_ja/tour/upper-type-bounds.md +++ b/_ja/tour/upper-type-bounds.md @@ -19,7 +19,7 @@ _上限型境界_ `T <: A` は型変数`T`が型`A`のサブタイプである こちらはクラス`PetContainer`の型パラメータの上限型境界を実演する例です。 -```tut +```scala mdoc abstract class Animal { def name: String } @@ -46,7 +46,7 @@ val dogContainer = new PetContainer[Dog](new Dog) val catContainer = new PetContainer[Cat](new Cat) ``` -```tut:fail +```scala mdoc:fail // これはコンパイルされません val lionContainer = new PetContainer[Lion](new Lion) ``` diff --git a/_ja/tour/variances.md b/_ja/tour/variances.md index 6ec894f79b..c7eb10304e 100644 --- a/_ja/tour/variances.md +++ b/_ja/tour/variances.md @@ -20,7 +20,7 @@ Scalaは[ジェネリッククラス](generic-classes.html)の型パラメータ もし変位指定が無ければ、クラスを抽象化して再利用しにくくなるでしょう。 -```tut +```scala mdoc class Foo[+A] // 共変クラス class Bar[-A] // 反変クラス class Baz[A] // 非変クラス @@ -34,7 +34,7 @@ class Baz[A] // 非変クラス このシンプルなクラス構成を考えてみましょう。 -```tut +```scala mdoc abstract class Animal { def name: String } @@ -49,7 +49,7 @@ Scala標準ライブラリにはイミュータブルなジェネリッククラ 以下の例では、メソッド`printAnimalNames`は引数に動物のリストを受け取り、新しい行にそれらの名前をプリントします。 もし`List[A]`が共変でなければ、最後の2つのメソッド呼び出しはコンパイルされず、`printAnimalNames`メソッドの使い勝手はひどく制限されます。 -```tut +```scala mdoc object CovarianceTest extends App { def printAnimalNames(animals: List[Animal]): Unit = { animals.foreach { animal => @@ -79,7 +79,7 @@ object CovarianceTest extends App { 先に定義された`Cat`、`Dog`、`Animal`クラスを以下の例で検討してみます。 -```tut +```scala mdoc abstract class Printer[-A] { def print(value: A): Unit } @@ -87,7 +87,7 @@ abstract class Printer[-A] { `Printer[A]`はある型`A`をどのようにプリントするかを知っている簡単なクラスです。 特定の型でいくつかのサブクラスを定義してみましょう。 -```tut +```scala mdoc class AnimalPrinter extends Printer[Animal] { def print(animal: Animal): Unit = println("The animal's name is: " + animal.name) @@ -104,7 +104,7 @@ class CatPrinter extends Printer[Cat] { 逆の関係性は適用されません、それは`Printer[Cat]`がコンソールに任意の`Animal`をプリントする方法を知らないからです。 したがって、私達は必要であれば`Printer[Animal]`を`Printer[Cat]`代わりに使うことができます。これは`Printer[A]`が反変であるからこそ可能なのです。 -```tut +```scala mdoc object ContravarianceTest extends App { val myCat: Cat = Cat("Boots") @@ -133,7 +133,7 @@ Scalaのジェネリッククラスは標準では非変です。 これは共変でも反変でもないことを意味します。 以下の例の状況では、`Container`クラスは非変です。`Container[Cat]`は`Container[Animal]`_ではなく_、逆もまた同様です。 -```tut +```scala mdoc class Container[A](value: A) { private var _value: A = value def getValue: A = _value @@ -164,7 +164,7 @@ val cat: Cat = catContainer.getValue // おっと、犬を猫に割り当てて 先ほど利用された`Cat`, `Dog`, `Animal`の継承ツリーに、以下のものを加えましょう: -```tut +```scala mdoc abstract class SmallAnimal extends Animal case class Mouse(name: String) extends SmallAnimal ``` diff --git a/_ko/tour/basics.md b/_ko/tour/basics.md index d52f7f85c9..21c8b94cdf 100644 --- a/_ko/tour/basics.md +++ b/_ko/tour/basics.md @@ -25,17 +25,17 @@ ScalaFiddle를 사용하면 브라우저에서 스칼라를 실행해 볼 수 이 페이지의 많은 예제 코드가 ScalaFiddle와 통합되어 있어 간단히 실행 버튼만 눌러 직접 실험해 볼 수 있다. ## 표현식 - + 표현식은 연산 가능한 명령문이다. -``` +```scala mdoc 1 + 1 ``` `println` 표현식을 사용해 결과를 출력할 수 있다. {% scalafiddle %} -```tut +```scala mdoc println(1) // 1 println(1 + 1) // 2 println("Hello!") // Hello! @@ -47,20 +47,20 @@ println("Hello," + " world!") // Hello, world! `val` 키워드로 표현식의 결과에 이름을 붙인다. -```tut +```scala mdoc val x = 1 + 1 println(x) // 2 ``` `x` 같이 이름이 붙여진 결과를 값이라고 부른다. 참조된 값은 재연산하지 않으며 값을 재할당할 수 없다. -```tut:fail +```scala mdoc:fail x = 3 // This does not compile. ``` 값의 타입을 추론할 수 있지만 명시적으로 타입을 지정할 수도 있다. -```tut +```scala mdoc:nest val x: Int = 1 + 1 ``` @@ -70,7 +70,7 @@ val x: Int = 1 + 1 변수는 재할당이 가능한 것 이외에는 값과 같다. `var` 키워드로 변수를 정의한다. -```tut +```scala mdoc:nest var x = 1 + 1 x = 3 // This compiles because "x" is declared with the "var" keyword. println(x * x) // 9 @@ -78,7 +78,7 @@ println(x * x) // 9 값처럼 명시적으로 타입을 지정할 수도 있다. -```tut +```scala mdoc:nest var x: Int = 1 + 1 ``` @@ -89,7 +89,7 @@ var x: Int = 1 + 1 블록 안 마지막 표현식의 결과는 블록 전체의 결과이기도 하다. -```tut +```scala mdoc println({ val x = 1 + 1 x + 1 @@ -102,7 +102,7 @@ println({ 주어진 정수에 1을 더하는 익명 함수(이름이 없는 함수)를 정의할 수 있다. -```tut +```scala mdoc (x: Int) => x + 1 ``` @@ -111,7 +111,7 @@ println({ 함수에 이름을 지정할 수 있다. {% scalafiddle %} -```tut +```scala mdoc val addOne = (x: Int) => x + 1 println(addOne(1)) // 2 ``` @@ -120,7 +120,7 @@ println(addOne(1)) // 2 함수는 여러 매개변수를 가질 수 있다. {% scalafiddle %} -```tut +```scala mdoc val add = (x: Int, y: Int) => x + y println(add(1, 2)) // 3 ``` @@ -128,7 +128,7 @@ println(add(1, 2)) // 3 또는 매개변수를 가지지 않을 수도 있다. -```tut +```scala mdoc val getTheAnswer = () => 42 println(getTheAnswer()) // 42 ``` @@ -140,7 +140,7 @@ println(getTheAnswer()) // 42 `def` 키워드로 메소드를 정의하고 이름, 매개변수 목록, 반환 타입 그리고 본문이 뒤따른다. {% scalafiddle %} -```tut +```scala mdoc:nest def add(x: Int, y: Int): Int = x + y println(add(1, 2)) // 3 ``` @@ -151,7 +151,7 @@ println(add(1, 2)) // 3 메소드는 여러 매개변수 목록을 가질 수 있다. {% scalafiddle %} -```tut +```scala mdoc def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier println(addThenMultiply(1, 2)(3)) // 9 ``` @@ -159,7 +159,7 @@ println(addThenMultiply(1, 2)(3)) // 9 또는 매개변수 목록을 가지지 않을 수도 있다. -```tut +```scala mdoc def name: String = System.getProperty("user.name") println("Hello, " + name + "!") ``` @@ -169,7 +169,7 @@ println("Hello, " + name + "!") 메소드는 여러 줄의 표현식을 가질 수 있다. {% scalafiddle %} -```tut +```scala mdoc def getSquareString(input: Double): String = { val square = input * input square.toString @@ -184,7 +184,7 @@ println(getSquareString(2.5)) // 6.25 `class` 키워드로 클래스를 정의하고 이름과 생성자 매개변수가 뒤따른다. -```tut +```scala mdoc class Greeter(prefix: String, suffix: String) { def greet(name: String): Unit = println(prefix + name + suffix) @@ -195,7 +195,7 @@ class Greeter(prefix: String, suffix: String) { `new` 키워드로 클래스의 인스턴스를 만든다. -```tut +```scala mdoc val greeter = new Greeter("Hello, ", "!") greeter.greet("Scala developer") // Hello, Scala developer! ``` @@ -206,13 +206,13 @@ greeter.greet("Scala developer") // Hello, Scala developer! 스칼라는 케이스 클래스라고 불리는 특별한 타입의 클래스를 가지고 있다. 기본적으로, 케이스 클래스는 변하지 않으며 값으로 비교한다. `case class` 키워드로 케이스 클래스를 정의한다. -```tut +```scala mdoc case class Point(x: Int, y: Int) ``` `new` 키워드 없이 케이스 클래스를 인스턴스화 할 수 있다. -```tut +```scala mdoc val point = Point(1, 2) val anotherPoint = Point(1, 2) val yetAnotherPoint = Point(2, 2) @@ -220,7 +220,7 @@ val yetAnotherPoint = Point(2, 2) 그리고 값으로 비교한다. -```tut +```scala mdoc if (point == anotherPoint) { println(point + " and " + anotherPoint + " are the same.") } else { @@ -242,7 +242,7 @@ if (point == yetAnotherPoint) { `object` 키워드로 객체를 정의한다. -```tut +```scala mdoc object IdFactory { private var counter = 0 def create(): Int = { @@ -254,7 +254,7 @@ object IdFactory { 객체 이름을 참조하여 객체에 접근할 수 있다. -```tut +```scala mdoc val newId: Int = IdFactory.create() println(newId) // 1 val newerId: Int = IdFactory.create() @@ -269,7 +269,7 @@ println(newerId) // 2 `trait` 키워드로 트레이트를 정의한다. -```tut +```scala mdoc:nest trait Greeter { def greet(name: String): Unit } @@ -278,7 +278,7 @@ trait Greeter { 또한 트레이트는 기본 구현도 가질 수 있다. {% scalafiddle %} -```tut +```scala mdoc:reset trait Greeter { def greet(name: String): Unit = println("Hello, " + name + "!") @@ -287,7 +287,7 @@ trait Greeter { `extends` 키워드로 트레이트를 상속할 수 있고 `override` 키워드로 구현을 오버라이드할 수 있다. -```tut +```scala mdoc class DefaultGreeter extends Greeter class CustomizableGreeter(prefix: String, postfix: String) extends Greeter { @@ -314,7 +314,7 @@ customGreeter.greet("Scala developer") // How are you, Scala developer? `object` 키워드를 사용하여 메인 메소드를 정의할 수 있다. -```tut +```scala mdoc object Main { def main(args: Array[String]): Unit = println("Hello, Scala developer!") diff --git a/_ko/tour/case-classes.md b/_ko/tour/case-classes.md index 1dcfe852be..78cf439c26 100644 --- a/_ko/tour/case-classes.md +++ b/_ko/tour/case-classes.md @@ -119,4 +119,4 @@ previous-page: multiple-parameter-lists * 값을 통한 비교는 여러분이 인스턴스들을 원시 값들인 것처럼 비교할수 있게 만들어 준다 - 클래스의 인스턴스들이 값 또는 참조를 통해 비교되는지와 같은 불확실성을 제거 * 패턴매칭은 로직의 분기를 심플하게 만들어주며, 결국 적은 버그와 가독성 높은 코드로 이어진다. -고광현 옮김 \ No newline at end of file +고광현 옮김 diff --git a/_ko/tour/classes.md b/_ko/tour/classes.md index 171079ebb3..a3635881a0 100644 --- a/_ko/tour/classes.md +++ b/_ko/tour/classes.md @@ -16,14 +16,14 @@ prerequisite-knowledge: no-return-keyword, type-declaration-syntax, string-inter # 클래스 정의 가장 단순한 클래스 정의는 예약어 `class`와 식별자만 있는 것입니다. 클래스명은 대문자로 시작하는 것이 관례입니다. -```tut +```scala mdoc class User val user1 = new User ``` 예약어 `new`는 클래스의 인스턴스를 만들기위해 사용합니다. `User` 클래스는 생성자를 정의하지 않았기 때문에 인자가 없는 기본 생성자를 갖습니다. 생성자와 클래스 몸체를 정의하고자 한다면, 다음의 클래스 정의 예제를 참고하십시오: -```tut +```scala mdoc class Point(var x: Int, var y: Int) { def move(dx: Int, dy: Int): Unit = { @@ -46,7 +46,7 @@ println(point1) // prints (2, 3) 생성자는 다음과 같은 기본 값을 제공하여 선택적 매개변수를 가질 수 있습니다: -```tut +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val origin = new Point // x and y are both set to 0 @@ -56,7 +56,7 @@ println(point1.x) // prints 1 ``` 이 버전의 `Point` 클래스에서 `x`와 `y` 인자는 기본 값 `0`을 가지므로 인자를 꼭 전달하지 않아도 됩니다. 생성자는 인자를 왼쪽부터 읽으므로 `y` 값만 전달하고 싶다면 매개변수의 이름을 지정해야 합니다. -``` +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val point2 = new Point(y=2) println(point2.y) // prints 2 @@ -66,7 +66,7 @@ println(point2.y) // prints 2 # Private 멤버와 Getter/Setter 문법 멤버는 기본적으로 public으로 지정됩니다. `private` 접근 지시자를 사용함으로써 클래스 외부로부터 멤버를 숨길 수 있습니다. -```tut +```scala mdoc:nest class Point { private var _x = 0 private var _y = 0 @@ -89,17 +89,17 @@ val point1 = new Point point1.x = 99 point1.y = 101 // 경고가 출력됩니다 ``` -이 버전의 `Point` 클래스에서는 데이터가 private 변수 `_x`와 `_y`에 저장됩니다. 이 private 데이터에 접근하기 위한 메서드 `def x`와 `def y`가 있고, `_x`와 `_y` 값을 검증하고 설정하기위한 `def x_=`와 `def y_=`가 있습니다. setter 메서드를 위한 특별한 문법에 주목하십시오: getter 메서드 식별자에 `_=`를 덧붙이고 매개변수가 뒤따르는 형식입니다. +이 버전의 `Point` 클래스에서는 데이터가 private 변수 `_x`와 `_y`에 저장됩니다. 이 private 데이터에 접근하기 위한 메서드 `def x`와 `def y`가 있고, `_x`와 `_y` 값을 검증하고 설정하기위한 `def x_=`와 `def y_=`가 있습니다. setter 메서드를 위한 특별한 문법에 주목하십시오: getter 메서드 식별자에 `_=`를 덧붙이고 매개변수가 뒤따르는 형식입니다. 기본 생성자에서 `val`와 `var`로 지정된 매개변수는 public 입니다. `val`은 불변을 의미하기 때문에 다음의 예처럼 값을 변경할 수 없습니다. -``` +```scala mdoc:fail class Point(val x: Int, val y: Int) val point = new Point(1, 2) point.x = 3 // <-- 컴파일되지 않습니다 ``` `val` 또는 `var`로 지정되지 않은 매개변수는 private 값이므로 클래스 내에서만 참조가능합니다. -``` +```scala mdoc:fail class Point(x: Int, y: Int) val point = new Point(1, 2) point.x // <-- 컴파일되지 않습니다 diff --git a/_ko/tour/implicit-conversions.md b/_ko/tour/implicit-conversions.md index 3b620ab090..41aa47856e 100644 --- a/_ko/tour/implicit-conversions.md +++ b/_ko/tour/implicit-conversions.md @@ -40,7 +40,7 @@ previous-page: implicit-parameters 예를 들면, `java.lang.Integer`를 기대하는 자바 메서드를 호출할 때, `scala.Int`를 대신 넘겨도 된다. 그 이유는 Predef가 아래 암시적 변환을 포함하기 때문이다. -```tut +```scala mdoc import scala.language.implicitConversions implicit def int2Integer(x: Int) = diff --git a/_ko/tour/inner-classes.md b/_ko/tour/inner-classes.md index 7588145c39..173449ef43 100644 --- a/_ko/tour/inner-classes.md +++ b/_ko/tour/inner-classes.md @@ -85,4 +85,4 @@ previous-page: lower-type-bounds > 이 프로그램에선 하나의 노드를 서로 다른 두 그래프에 추가할 수 없음에 주의하자. 이 제약도 함께 제거하기 위해선 변수 nodes의 타입을 `Graph#Node`로 바꿔야 한다. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/lower-type-bounds.md b/_ko/tour/lower-type-bounds.md index b5a99e2f19..718983a0a4 100644 --- a/_ko/tour/lower-type-bounds.md +++ b/_ko/tour/lower-type-bounds.md @@ -47,4 +47,4 @@ _주의:_ 새로운 `prepend` 메소드에선 타입의 제약이 조금 줄어 val anyList: ListNode[Any] = strList.prepend(12345) } -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/multiple-parameter-lists.md b/_ko/tour/multiple-parameter-lists.md index ea0ed2fa73..c8cf38cfdc 100644 --- a/_ko/tour/multiple-parameter-lists.md +++ b/_ko/tour/multiple-parameter-lists.md @@ -35,4 +35,4 @@ _주의: `modN` 메소드는 두 번의 `filter` 호출에서 부분적으로 List(2,4,6,8) List(3,6) -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/named-arguments.md b/_ko/tour/named-arguments.md index 7386c3c563..53fa5182a9 100644 --- a/_ko/tour/named-arguments.md +++ b/_ko/tour/named-arguments.md @@ -33,4 +33,4 @@ previous-page: default-parameter-values 여러분이 원하는 순서대로 파라미터를 위치시킬 수 있기 때문에 파라미터 목록 중에서 가장 중요한 파라미터부터 기본 값을 사용할 수 있다. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/nested-functions.md b/_ko/tour/nested-functions.md index ba90ee4a60..a26a6a64a3 100644 --- a/_ko/tour/nested-functions.md +++ b/_ko/tour/nested-functions.md @@ -29,4 +29,4 @@ _주의: 중첩 함수 `process`는 `filter`의 파라미터 값으로써 외부 List(1,2,3,4) -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/packages-and-imports.md b/_ko/tour/packages-and-imports.md index c978597d53..4a40cf7bf5 100644 --- a/_ko/tour/packages-and-imports.md +++ b/_ko/tour/packages-and-imports.md @@ -78,7 +78,7 @@ import users.{UserPreferences => UPrefs} // 편의를 위해 이름을 바꾸 스칼라가 자바와 한가지 다른 점은 어디서든 임포트를 할 수 있다는 것이다. -```tut +```scala mdoc def sqrtplus1(x: Int) = { import scala.math.sqrt sqrt(x) + 1.0 diff --git a/_ko/tour/pattern-matching.md b/_ko/tour/pattern-matching.md index e860caed3a..3ee2efd1d0 100644 --- a/_ko/tour/pattern-matching.md +++ b/_ko/tour/pattern-matching.md @@ -40,4 +40,4 @@ previous-page: case-classes 스칼라의 패턴 매칭 명령문은 [케이스 클래스](case-classes.html)를 통해 표현되는 대수 타입과 매칭할 때 가장 유용하다. 또한 스칼라는 [추출자 오브젝트](extractor-objects.html)의 `unapply` 메소드를 사용해, 독립적인 케이스 클래스로 패턴을 정의할 수 있도록 해준다. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/regular-expression-patterns.md b/_ko/tour/regular-expression-patterns.md index 12ffd6caae..4f71d15e49 100644 --- a/_ko/tour/regular-expression-patterns.md +++ b/_ko/tour/regular-expression-patterns.md @@ -40,4 +40,4 @@ previous-page: singleton-objects 정규 표현식 패턴이 XML 처리에 예상에 비해 그다지 유용하지 않다는 것이 우리의 의견이다. 실제 상황에서 XML를 처리해야하는 애플리케이션이라면 XPath가 더 나은 선택으로 보인다. 우리의 변환이나 정규 표현식 패턴에 드물지만 제거하기 어려운 난해한 버그가 있다는 점을 발견했을 때, 우리는 이 기회에 언어를 좀 더 단순하게 만들기로 결정했다. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/self-types.md b/_ko/tour/self-types.md index bd99c389c7..56ca99a2e6 100644 --- a/_ko/tour/self-types.md +++ b/_ko/tour/self-types.md @@ -98,4 +98,4 @@ previous-page: compound-types n1.connectWith(n3) } -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/singleton-objects.md b/_ko/tour/singleton-objects.md index 64f14c43f6..bc5ffaa359 100644 --- a/_ko/tour/singleton-objects.md +++ b/_ko/tour/singleton-objects.md @@ -34,7 +34,7 @@ object Blah { 하나의 클래스와 그 동반자 객체는 어떤 경우라도, 아래와 같이 *같은* 소스파일에 정의되어야 한다. -```tut +```scala mdoc class IntPair(val x: Int, val y: Int) object IntPair { diff --git a/_ko/tour/traits.md b/_ko/tour/traits.md index 655a5557b3..1dd3fb34d9 100644 --- a/_ko/tour/traits.md +++ b/_ko/tour/traits.md @@ -16,12 +16,12 @@ prerequisite-knowledge: expressions, classes, generics, objects, companion-objec # 트레잇 정의 가장 단순한 트레잇 정의는 예약어 `trait`과 식별자만 있는 것입니다: -```tut +```scala mdoc trait HairColor ``` 트레잇은 제네릭 타입과 추상 메서드로 특히 유용합니다. -```tut +```scala mdoc trait Iterator[A] { def hasNext: Boolean def next(): A @@ -32,7 +32,7 @@ trait Iterator[A] { ## 트레잇 사용하기 `extends` 예약어를 사용하여 트레잇을 확장하십시오. 그런 다음 `override` 예약어를 사용하여 트레잇의 추상 멤버를 구현하십시오: -```tut +```scala mdoc:nest trait Iterator[A] { def hasNext: Boolean def next(): A @@ -59,7 +59,7 @@ iterator.next() // returns 1 ## 서브타이핑 특정 트레잇이 필요한 곳에 그 트레잇의 서브타입을 대신 사용할 수 있습니다. -```tut +```scala mdoc import scala.collection.mutable.ArrayBuffer trait Pet { diff --git a/_ko/tour/tuples.md b/_ko/tour/tuples.md index e699f7f78f..e4b7ff32c0 100644 --- a/_ko/tour/tuples.md +++ b/_ko/tour/tuples.md @@ -18,7 +18,7 @@ topics: tuples 두개의 엘리먼트를 갖는 튜플은 다음과 같이 생성할 수 있다: -```tut +```scala mdoc val ingredient = ("Sugar" , 25) ``` @@ -33,7 +33,7 @@ val ingredient = ("Sugar" , 25) 튜플의 엘리먼트에 접근하기 위한 한가지 방법은 위치로 접근하는 것이다. 각 요소들은 `_1`, `_2`, ... 와 같은 이름을 갖는다. -```tut +```scala mdoc println(ingredient._1) // Sugar println(ingredient._2) // 25 ``` @@ -42,7 +42,7 @@ println(ingredient._2) // 25 하나의 튜플은 패턴 매칭을 사용하여 분리할 수 있다: -```tut +```scala mdoc val (name, quantity) = ingredient println(name) // Sugar println(quantity) // 25 @@ -52,7 +52,7 @@ println(quantity) // 25 여기 튜플을 패턴 매칭한 또 다른 예제가 있다: -```tut +```scala mdoc val planets = List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6), ("Mars", 227.9), ("Jupiter", 778.3)) @@ -65,7 +65,7 @@ planets.foreach{ 또는 `for` comprehension에서: -```tut +```scala mdoc val numPairs = List((2, 5), (3, -7), (20, 56)) for ((a, b) <- numPairs) { println(a * b) diff --git a/_ko/tour/type-inference.md b/_ko/tour/type-inference.md index c3daf79e72..189b334593 100644 --- a/_ko/tour/type-inference.md +++ b/_ko/tour/type-inference.md @@ -51,4 +51,4 @@ previous-page: polymorphic-methods 이 프로그램은 변수 `obj`의 타입 추론이 `Null`이기 때문에 컴파일되지 않는다. 해당 타입의 유일한 값이 `null`이기 때문에 이 변수는 다른 값을 나타낼 수 없다. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/unified-types.md b/_ko/tour/unified-types.md index 3b13b95978..989ef50d6b 100644 --- a/_ko/tour/unified-types.md +++ b/_ko/tour/unified-types.md @@ -27,7 +27,7 @@ prerequisite-knowledge: classes, basics 다음 소스는 문자열 값, 정수 값, 문자 값, boolean 값과 함수 역시 모두 객체로 취급됨을 보여주는 샘플입니다: -```tut +```scala mdoc val list: List[Any] = List( "a string", 732, // 정수 값 @@ -57,7 +57,7 @@ true 예제: -```tut +```scala mdoc val x: Long = 987654321 val y: Float = x // 9.8765434E8 (이 경우 일부 자리수가 소실되었음을 주의) diff --git a/_ko/tour/variances.md b/_ko/tour/variances.md index 7cc2b404ac..b8049a6a5c 100644 --- a/_ko/tour/variances.md +++ b/_ko/tour/variances.md @@ -14,7 +14,7 @@ previous-page: generic-classes [제네릭 클래스](generic-classes.html)에 관한 페이지에선 변경 가능한 스택의 예제를 살펴보면서, 클래스 `Stack[T]`에서 정의한 타입은 타입 파라미터의 서브타입이 불변자여야 함을 설명했었다. 이는 추상화된 클래스의 재사용을 제한할 수 있다. 지금부턴 이런 제약이 없는 함수형(즉, 변경이 불가능한) 스택의 구현을 알아본다. 이 구현은 [다형성 메소드](polymorphic-methods.html), [하위 타입 경계](lower-type-bounds.html), 순가변 타입 파라미터 어노테이션 등의 중요 개념을 조합한 좀 더 어려운 예제임을 알아두자. 또한 [내부 클래스](inner-classes.html)를 사용해 명시적인 연결 없이도 스택의 항목을 서로 묶을 수 있도록 만들었다. -```tut +```scala mdoc class Stack[+T] { def push[S >: T](elem: S): Stack[S] = new Stack[S] { override def top: S = elem diff --git a/_overviews/contributors/index.md b/_overviews/contributors/index.md index 4a685c7a70..0c6ed3482a 100644 --- a/_overviews/contributors/index.md +++ b/_overviews/contributors/index.md @@ -496,13 +496,13 @@ For instance, given the following `src/documentation/getting-started.md` file: First, start with the following import: -```tut +```scala import ch.epfl.scala.Example ``` Then, do nothing with something: -```tut +```scala Example.doNothing(42) ``` {% endhighlight %} diff --git a/_overviews/core/custom-collection-operations.md b/_overviews/core/custom-collection-operations.md index 87b2f863ae..25f792fd7a 100644 --- a/_overviews/core/custom-collection-operations.md +++ b/_overviews/core/custom-collection-operations.md @@ -118,7 +118,7 @@ res2: Set[Int] = HashSet(-1775377531, -1376640531, -1009522404, 526943297, 14318 A very basic definition of `Gen[A]` could be the following: -```tut +```scala mdoc trait Gen[A] { /** Get a generated value of type `A` */ def get: A @@ -127,7 +127,7 @@ trait Gen[A] { And the following instances can be defined: -```tut +```scala mdoc import scala.util.Random object Gen { @@ -330,4 +330,4 @@ be `List[Int]`. - To also support `String`, `Array` and `View`, use `IsIterable`, - To produce a collection given its type, use a `Factory`, - To produce a collection based on the type of a source collection and the type of elements of the collection - to produce, use `BuildFrom`. \ No newline at end of file + to produce, use `BuildFrom`. diff --git a/_overviews/scaladoc/contribute.md b/_overviews/scaladoc/contribute.md index c922afa863..c902e99f97 100644 --- a/_overviews/scaladoc/contribute.md +++ b/_overviews/scaladoc/contribute.md @@ -25,4 +25,4 @@ which covers the steps and workflow necessary work on the Scaladoc tool. As of Scala 2.13, the Scaladoc tool is maintained but not actively developed. Major development of Scaladoc will progress as a part of Dotty for Scala 3 in the -[Dottydoc](https://dotty.epfl.ch/docs/usage/dottydoc.html) tool. \ No newline at end of file +[Dottydoc](https://dotty.epfl.ch/docs/usage/dottydoc.html) tool. diff --git a/_pl/tour/abstract-type-members.md b/_pl/tour/abstract-type-members.md index b8f6b7770f..d47ebe86af 100644 --- a/_pl/tour/abstract-type-members.md +++ b/_pl/tour/abstract-type-members.md @@ -13,7 +13,7 @@ W Scali klasy są parametryzowane wartościami (parametry konstruktora) oraz typ Poniższy przykład definiuje wartość określaną przez abstrakcyjny typ będący elementem [cechy](traits.html) `Buffer`: -```tut +```scala mdoc trait Buffer { type T val element: T @@ -24,7 +24,7 @@ trait Buffer { W poniższym programie definiujemy klasę `SeqBuffer`, która ogranicza możliwe typy `T` do pochodnych sekwencji `Seq[U]` dla nowego typu `U`: -```tut +```scala mdoc:nest abstract class SeqBuffer extends Buffer { type U type T <: Seq[U] @@ -34,7 +34,7 @@ abstract class SeqBuffer extends Buffer { Cechy oraz [klasy](classes.html) z abstrakcyjnymi typami są często używane w połączeniu z anonimowymi klasami. Aby to zilustrować, wykorzystamy program, w którym utworzymy bufor sekwencji ograniczony do listy liczb całkowitych: -```tut +```scala mdoc:nest abstract class IntSeqBuffer extends SeqBuffer { type U = Int } @@ -55,7 +55,7 @@ Typ zwracany przez metodę `newIntSeqBuf` nawiązuje do specjalizacji cechy `Buf Warto zwrócić uwagę, że często jest możliwa zamiana abstrakcyjnych typów w parametry typów klas i odwrotnie. Poniższy przykład stosuje wyłącznie parametry typów: -```tut +```scala mdoc:nest abstract class Buffer[+T] { val element: T } diff --git a/_pl/tour/automatic-closures.md b/_pl/tour/automatic-closures.md index d0aaca2161..5f28a2568a 100644 --- a/_pl/tour/automatic-closures.md +++ b/_pl/tour/automatic-closures.md @@ -13,7 +13,7 @@ Scala pozwala na przekazywanie funkcji bezparametrycznych jako argumenty dla met Poniższy kod demonstruje działanie tego mechanizmu: -```tut +```scala mdoc object TargetTest1 extends App { def whileLoop(cond: => Boolean)(body: => Unit): Unit = if (cond) { @@ -34,7 +34,7 @@ Możemy połączyć ze sobą wykorzystanie [operatorów infiksowych/postfiksowyc Oto implementacja pętli w stylu wykonaj-dopóki: -```tut +```scala mdoc object TargetTest2 extends App { def loop(body: => Unit): LoopUnlessCond = new LoopUnlessCond(body) diff --git a/_pl/tour/basics.md b/_pl/tour/basics.md index 932bb890c7..903ecdcfe7 100644 --- a/_pl/tour/basics.md +++ b/_pl/tour/basics.md @@ -28,14 +28,14 @@ dzięki czemu można je wypróbować wciskając po prostu przycisk "Run". Wyrażenia są rezultatem ewaluacji fragmentów kodu. -``` +```scala mdoc 1 + 1 ``` Wyniki wyrażeń można wyświetlić za pomocą funkcji `println`. {% scalafiddle %} -```tut +```scala mdoc println(1) // 1 println(1 + 1) // 2 println("Hello!") // Hello! @@ -47,7 +47,7 @@ println("Hello," + " world!") // Hello, world! Rezultaty wyrażeń mogą zostać nazwane za pomocą słowa kluczowego `val`. -```tut +```scala mdoc val x = 1 + 1 println(x) // 2 ``` @@ -57,13 +57,13 @@ Odniesienie się do wartości nie powoduje jej ponownego obliczenia. Wartości nie można przypisać ponownie. -```tut:fail +```scala mdoc:fail x = 3 // Nie kompiluje się. ``` Typy wartości mogą być wywnioskowane przez kompilator, ale można również wyraźnie określić type: -```tut +```scala mdoc:nest val x: Int = 1 + 1 ``` @@ -75,7 +75,7 @@ Zmienne są podobne do wartości, ale z tym wyjątkiem, że można je ponownie p Zmienną można zdefiniować używając słowa kluczowego `var`. {% scalafiddle %} -```tut +```scala mdoc:nest var x = 1 + 1 x = 3 // Kompiluje się, ponieważ "x" jest zdefiniowane z użyciem "var". println(x * x) // 9 @@ -84,7 +84,7 @@ println(x * x) // 9 Tak jak przy wartościach, można wyraźnie zdefiniować żądany typ: -```tut +```scala mdoc:nest var x: Int = 1 + 1 ``` @@ -95,7 +95,7 @@ Taką konstrukcję nazywamy blokiem. Wynikiem całego bloku kodu jest wynik ostatniego wyrażenia w tym bloku. {% scalafiddle %} -```tut +```scala mdoc println({ val x = 1 + 1 x + 1 @@ -109,7 +109,7 @@ Funkcje to wyrażenia, które przyjmują pewne parametry. Poniżej zdefiniowana jest funkcja anonimowa (nieposiadająca nazwy), która zwraca liczbę całkowitą przekazaną jako parametr, zwiększoną o 1. -```tut +```scala mdoc (x: Int) => x + 1 ``` @@ -119,7 +119,7 @@ Po prawej stronie - wyrażenie wykorzystujące te parametry. Funkcje można również nazywać. {% scalafiddle %} -```tut +```scala mdoc val addOne = (x: Int) => x + 1 println(addOne(1)) // 2 ``` @@ -128,7 +128,7 @@ println(addOne(1)) // 2 Funkcje mogą przyjmować wiele parametrów. {% scalafiddle %} -```tut +```scala mdoc val add = (x: Int, y: Int) => x + y println(add(1, 2)) // 3 ``` @@ -137,7 +137,7 @@ println(add(1, 2)) // 3 Mogą też wcale nie mieć parametrow. {% scalafiddle %} -```tut +```scala mdoc val getTheAnswer = () => 42 println(getTheAnswer()) // 42 ``` @@ -151,7 +151,7 @@ Metody są definiowane z użyciem słowa kluczowego `def`. Po `def` następuje nazwa metody, lista parametrów, zwracany typ i ciało metody. {% scalafiddle %} -```tut +```scala mdoc:nest def add(x: Int, y: Int): Int = x + y println(add(1, 2)) // 3 ``` @@ -162,7 +162,7 @@ Zauważ, że zwracany typ jest zadeklarowany _po_ liście parametrów i dwukropk Metody mogą mieć wiele list parametrów. {% scalafiddle %} -```tut +```scala mdoc def addThenMultiply(x: Int, y: Int)(multiplier: Int): Int = (x + y) * multiplier println(addThenMultiply(1, 2)(3)) // 9 ``` @@ -171,7 +171,7 @@ println(addThenMultiply(1, 2)(3)) // 9 Mogą również wcale ich nie posiadać. {% scalafiddle %} -```tut +```scala mdoc def name: String = System.getProperty("user.name") println("Hello, " + name + "!") ``` @@ -182,7 +182,7 @@ Od funkcji odróżnia je jeszcze kilka innych rzeczy, ale na razie możesz o nic Metody mogą zawierać również wyrażenia wielowierszowe. {% scalafiddle %} -```tut +```scala mdoc def getSquareString(input: Double): String = { val square = input * input square.toString @@ -199,7 +199,7 @@ Scala posiada słowo kluczowe `return`, ale jest ono wykorzystywane bardzo rzadk Klasy są definiowane za pomocą słowa kluczowego `class`, po którym następuje nazwa klasy i parametry konstruktora. {% scalafiddle %} -```tut +```scala mdoc class Greeter(prefix: String, suffix: String) { def greet(name: String): Unit = println(prefix + name + suffix) @@ -212,7 +212,7 @@ Różnica polega na tym, że w Scali każde wyrażenie musi zwracać jakąś war Nowe instancje klasy tworzy się za pomocą słowa kluczowego `new`. -```tut +```scala mdoc val greeter = new Greeter("Hello, ", "!") greeter.greet("Scala developer") // Hello, Scala developer! ``` @@ -227,13 +227,13 @@ Klasy przypadku są domyślnie niezmienne i porównywane przez wartości. Klasy te można definiować używająć słów kluczowych `case class`. {% scalafiddle %} -```tut +```scala mdoc case class Point(x: Int, y: Int) ``` Do utworzenia nowej instacji klasy przypadku nie jest konieczne używanie słowa kluczowego `new`. -```tut +```scala mdoc val point = Point(1, 2) val anotherPoint = Point(1, 2) val yetAnotherPoint = Point(2, 2) @@ -241,7 +241,7 @@ val yetAnotherPoint = Point(2, 2) Są one porównywane przez wartości - _nie_ przez referencje. -```tut +```scala mdoc if (point == anotherPoint) { println(point + " i " + anotherPoint + " są jednakowe.") } else { @@ -267,7 +267,7 @@ Można o nich myśleć jak o instancjach ich własnych klas - singletonach. Objekty definiuje się z użyciem słowa kluczowego `object`. {% scalafiddle %} -```tut +```scala mdoc object IdFactory { private var counter = 0 def create(): Int = { @@ -279,7 +279,7 @@ object IdFactory { Aby uzyskać dostęp do obiektu używa się jego nazwy. -```tut +```scala mdoc val newId: Int = IdFactory.create() println(newId) // 1 val newerId: Int = IdFactory.create() @@ -296,7 +296,7 @@ Wiele cech może być łączonych. Cechę (trait) można zdefiniować używając słowa kluczowego `trait`. -```tut +```scala mdoc:nest trait Greeter { def greet(name: String): Unit } @@ -305,7 +305,7 @@ trait Greeter { Cechy mogą zawierać domyślną implementację. {% scalafiddle %} -```tut +```scala mdoc:reset trait Greeter { def greet(name: String): Unit = println("Hello, " + name + "!") @@ -314,7 +314,7 @@ trait Greeter { Cechy można rozszerzać używając słowa kluczowego `extends` i nadpisać implementację z użyciem `override`. -```tut +```scala mdoc class DefaultGreeter extends Greeter class CustomizableGreeter(prefix: String, postfix: String) extends Greeter { @@ -342,7 +342,7 @@ Maszyna Wirtalna Javy (Java Virtual Machine / JVM) wymaga, aby metoda ta nazywa Z użyciem obiektu można zdefiniować metodę `main` w następujący sposób: -```tut +```scala mdoc object Main { def main(args: Array[String]): Unit = println("Hello, Scala developer!") diff --git a/_pl/tour/by-name-parameters.md b/_pl/tour/by-name-parameters.md index 2bf59f5ef6..21cf9cc758 100644 --- a/_pl/tour/by-name-parameters.md +++ b/_pl/tour/by-name-parameters.md @@ -11,7 +11,7 @@ language: pl _Parametry przekazywane według nazwy_ są ewaluowane za każdym razem gdy są używane. Nie zostaną w ogóle wyewaluowane jeśli nie będą używane. Jest to podobne do zastępowania parametrów w ciele funkcji wyrażeniami podanymi w miejscu jej wywołania. Są przeciwieństwem do _parametrów przekazywanych według wartości_. Aby utworzyć parametr przekazywany według nazwy, po prostu dodaj `=>` przed jego typem. -```tut +```scala mdoc def calculate(input: => Int) = input * 37 ``` @@ -19,7 +19,7 @@ Parametry przekazywane według nazwy mają tę zaletę że nie są ewaluowane je Oto przykład, jak możemy zaimplementować pętlę while: -```tut +```scala mdoc def whileLoop(condition: => Boolean)(body: => Unit): Unit = if (condition) { body diff --git a/_pl/tour/case-classes.md b/_pl/tour/case-classes.md index fcf4bd1f57..cc7346a277 100644 --- a/_pl/tour/case-classes.md +++ b/_pl/tour/case-classes.md @@ -18,7 +18,7 @@ W dalszych rozdziałach przyjrzymy się jak przydają się w [dopasowywaniu wzor Minimalna definicja klasy przypadku wymaga słów kluczowych `case class`, identyfikatora oraz listy parametrów (może być pusta): -```tut +```scala mdoc case class Book(isbn: String) val frankenstein = Book("978-0486282114") @@ -44,7 +44,7 @@ Alternatywnie, w klasach przypadków można też używać `var`, jednak stanowc Klasy przypadków są porównywane według ich struktury, a nie przez referencje: -```tut +```scala mdoc case class Message(sender: String, recipient: String, body: String) val message2 = Message("jorge@catalonia.es", "guillaume@quebec.ca", "Com va?") @@ -59,7 +59,7 @@ Mimo, że `message1` oraz `message2` odnoszą się do innych obiektów, to ich w Możliwe jest stworzenie płytkiej kopii (ang. shallow copy) instancji klasy przypadku używając metody `copy`. Opcjonalnie można zmienić jeszcze wybrane parametry konstruktora. -```tut +```scala mdoc:nest case class Message(sender: String, recipient: String, body: String) val message4 = Message("julien@bretagne.fr", "travis@washington.us", "Me zo o komz gant ma amezeg") val message5 = message4.copy(sender = message4.recipient, recipient = "claire@bourgogne.fr") diff --git a/_pl/tour/classes.md b/_pl/tour/classes.md index 6325c3c2f8..00a4734cbd 100644 --- a/_pl/tour/classes.md +++ b/_pl/tour/classes.md @@ -18,7 +18,7 @@ Typy, obiekty i cechy zostaną omówione w dalszej części przewodnika. Minimalna definicja klasy składa się ze słowa kluczowego `class` oraz jej identyfikatora. Nazwy klas powinny zaczynać się z wielkiej litery. -```tut +```scala mdoc class User val user1 = new User @@ -29,7 +29,7 @@ Ponieważ żaden konstruktor nie został zdefiniowany, klasa `User` posiada kons Zazwyczaj jednak definiujemy konstruktor i ciało klasy. Poniższy przykład przedstawia definicję klasy służącej do reprezentowania punktu. -```tut +```scala mdoc class Point(var x: Int, var y: Int) { def move(dx: Int, dy: Int): Unit = { @@ -57,7 +57,7 @@ Ponieważ `toString` nadpisuje metodę `toString` zdefiniowaną w [`AnyRef`](un Konstruktory mogą zawierać parametry opcjonalne - wystarczy dostarczyć wartość domyślną dla takiego parametru. -```tut +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val origin = new Point // x i y są mają wartość 0 @@ -69,7 +69,7 @@ println(point1.x) // wyświetla 1 W tej wersji klasy `Point`, `x` oraz `y` mają domyślną wartość `0` - dlatego nie jest wymagane przekazanie żadnych parametrów. Jednak z powodu tego, że konstruktor jest ewaluowany od lewej do prawej strony, jeżeli chcesz przekazać parametr tylko do argumentu `y`, musisz określić nazwę tego parametru. -``` +```scala mdoc:nest class Point(var x: Int = 0, var y: Int = 0) val point2 = new Point(y = 2) println(point2.y) // wyświetla 2 @@ -82,7 +82,7 @@ Jest to również dobra praktyka, która zwiększa przejrzystość kodu. Domyślnie wszystkie składniki klasy są publiczne. Aby ukryć je przed zewnętrznymi klientami (wszystkim co jest poza daną klasą), należy użyć słowa kluczowego `private`. -```tut +```scala mdoc:nest class Point { private var _x = 0 private var _y = 0 @@ -114,7 +114,7 @@ Zwróć uwagę na specyficzną składnię dla setterów: posiadają one `_=` do Parametry głównego konstruktora oznaczone przez `val` i `var` są publiczne. Ponieważ `val` jest niezmienne, poniższy kod nie jest prawidłowy -``` +```scala mdoc:fail class Point(val x: Int, val y: Int) val point = new Point(1, 2) point.x = 3 // <-- nie kompiluje się @@ -122,7 +122,7 @@ point.x = 3 // <-- nie kompiluje się Parametry konstruktora __nie__ zawierające `val` lub `var` są prywatne - widoczne jedynie we wnętrzu klasy. -``` +```scala mdoc:fail class Point(x: Int, y: Int) val point = new Point(1, 2) point.x // <-- nie kompiluje się diff --git a/_pl/tour/compound-types.md b/_pl/tour/compound-types.md index ffe86317b6..c60b379f7b 100644 --- a/_pl/tour/compound-types.md +++ b/_pl/tour/compound-types.md @@ -13,7 +13,7 @@ Czasami konieczne jest wyrażenie, że dany typ jest podtypem kilku innych typó Załóżmy, że mamy dwie cechy `Cloneable` i `Resetable`: -```tut +```scala mdoc trait Cloneable extends java.lang.Cloneable { override def clone(): Cloneable = { super.clone().asInstanceOf[Cloneable] diff --git a/_pl/tour/default-parameter-values.md b/_pl/tour/default-parameter-values.md index 94883f7cd8..460356deaf 100644 --- a/_pl/tour/default-parameter-values.md +++ b/_pl/tour/default-parameter-values.md @@ -50,7 +50,7 @@ Mimo że powstrzymuje to nas od powtarzania się, to podejście nie jest zbyt wy Scala wprowadza bezpośrednie wsparcie dla domyślnych parametrów: -```tut +```scala mdoc class HashMap[K,V](initialCapacity: Int = 16, loadFactor: Float = 0.75f) { } diff --git a/_pl/tour/extractor-objects.md b/_pl/tour/extractor-objects.md index ee974014f0..17fa3461d7 100644 --- a/_pl/tour/extractor-objects.md +++ b/_pl/tour/extractor-objects.md @@ -11,7 +11,7 @@ previous-page: regular-expression-patterns W Scali wzorce mogą być zdefiniowane niezależnie od klas przypadków. Obiekt posiadający metodę `unapply` może funkcjonować jako tak zwany ekstraktor. Jest to szczególna metoda, która pozwala na odwrócenie zastosowania obiektu dla pewnych danych. Jego celem jest ekstrakcja danych, z których został on utworzony. Dla przykładu, poniższy kod definiuje ekstraktor dla [obiektu](singleton-objects.html) `Twice`: -```tut +```scala mdoc object Twice { def apply(x: Int): Int = x * 2 def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None diff --git a/_pl/tour/for-comprehensions.md b/_pl/tour/for-comprehensions.md index 4e70b1627a..6d0c3ab0c9 100644 --- a/_pl/tour/for-comprehensions.md +++ b/_pl/tour/for-comprehensions.md @@ -16,7 +16,7 @@ _For comprehensions_ przedstawione jest w formie `for (enumerators) yield e`, gd Poniżej znajduje się przykład, który przekształca listę osób na listę imion osób, których wiek mieści się w przedziale od 30 do 40 lat. -```tut +```scala mdoc case class Person(name: String, age: Int) val people = List( @@ -37,7 +37,7 @@ Na początku `for` znajduje się generator `person <- people`. Następujące po Poniżej znajduje się bardziej złożony przykład, który używa dwóch generatorów. Jego zadaniem jest sprawdzenie wszystkich par liczb od `0` do `n-1` i wybór tylko tych par, których wartości są sobie równe. -```tut +```scala mdoc def someTuple(n: Int) = for ( i <- 0 until n; @@ -63,7 +63,7 @@ Załóżmy, że mamy dwie wartości `Option[String]` i chcielibyśmy zwrócić o Spójrzmy poniżej: -```tut +```scala mdoc case class Student(name: String, surname: String) val nameOpt: Option[String] = Some("John") @@ -80,7 +80,7 @@ Jeżeli `name` lub `surname` nie byłyby określone, np. przyjmowałyby wartoś Wszystkie powyższe przykłady posiadały wyrażenie `yield` na końcu _comprehensions_, jednak nie jest to obligatoryjne. Gdy `yield` nie zostanie dodanie zwrócony zostanie `Unit`. Takie rozwiązanie może być przydatne gdy chcemy uzyskać jakieś skutki uboczne. Poniższy przykład wypisuje liczby od 0 do 9 bez użycia `yield`. -```tut +```scala mdoc def count(n: Int) = for (i <- 0 until n) println(s"$i ") diff --git a/_pl/tour/generic-classes.md b/_pl/tour/generic-classes.md index 5552d9931f..69599e9b7e 100644 --- a/_pl/tour/generic-classes.md +++ b/_pl/tour/generic-classes.md @@ -13,7 +13,7 @@ Scala posiada wbudowaną obsługą klas parametryzowanych przez typy. Tego typu Poniższy przykład demonstruje zastosowanie parametrów generycznych: -```tut +```scala mdoc class Stack[T] { var elems: List[T] = Nil def push(x: T) { elems = x :: elems } @@ -26,7 +26,7 @@ Klasa `Stack` modeluje zmienny stos zawierający elementy dowolnego typu `T`. Pa Przykłady zastosowania: -```tut +```scala mdoc object GenericsTest extends App { val stack = new Stack[Int] stack.push(1) diff --git a/_pl/tour/higher-order-functions.md b/_pl/tour/higher-order-functions.md index 7180e0a351..2a1a919e04 100644 --- a/_pl/tour/higher-order-functions.md +++ b/_pl/tour/higher-order-functions.md @@ -16,7 +16,7 @@ Terminologia może w tym momencie wydawać się niejasna, pojęcie "funkcja wyż Jednym z najczęściej spotykanych przykładów funkcji wyższego rzędu jest funkcja `map`, która dostępna jest dla kolekcji w Scali. -```tut +```scala mdoc val salaries = Seq(20000, 70000, 40000) val doubleSalary = (x: Int) => x * 2 val newSalaries = salaries.map(doubleSalary) // List(40000, 140000, 80000) @@ -37,7 +37,7 @@ Zauważ, że w powyższym przykładzie `x` nie jest zadeklarowane jako typ `Int` Dzieje się tak, ponieważ kompilator może wywnioskować typ, bazując na typie funkcji oczekiwanej przez `map`. Poniżej jeszcze bardziej idiomatyczny sposób napisania tego kodu: -```tut +```scala mdoc:nest val salaries = Seq(20000, 70000, 40000) val newSalaries = salaries.map(_ * 2) ``` @@ -67,7 +67,7 @@ Jednym z powodów użycia funkcji wyższego rzędu jest zredukowanie nadmiaroweg Powiedzmy, że chcemy stworzyć metody, które potrafią zwiększyć czyjeś wynagrodzenie wg. jakiegoś współczynnika. Bez użycia funkcji wyższego rzędu mogłoby to wyglądać w następujący sposób: -```tut +```scala mdoc object SalaryRaiser { def smallPromotion(salaries: List[Double]): List[Double] = @@ -84,7 +84,7 @@ object SalaryRaiser { Zauważ, że każda z trzech metod różni się jedynie współczynnikiem z jakim zmienia wynagrodzenie. Aby to uprościć, możemy wydzielić powtórzony kod do funkcji wyższego rzędu: -```tut +```scala mdoc:nest object SalaryRaiser { private def promotion(salaries: List[Double], promotionFunction: Double => Double): List[Double] = @@ -108,7 +108,7 @@ Nowa metoda, `promotion`, przyjmuje jako parametr listę wynagrodzeń oraz funkc Istnieją pewne sytuacje, kiedy chcemy wygenerować jakieś funkcje. Oto przykład funkcji zwracającej inną funkcję. -```tut +```scala mdoc def urlBuilder(ssl: Boolean, domainName: String): (String, String) => String = { val schema = if (ssl) "https://" else "http://" (endpoint: String, query: String) => s"$schema$domainName/$endpoint?$query" diff --git a/_pl/tour/implicit-conversions.md b/_pl/tour/implicit-conversions.md index 86d7fa829e..d859139ee8 100644 --- a/_pl/tour/implicit-conversions.md +++ b/_pl/tour/implicit-conversions.md @@ -40,7 +40,7 @@ Domyślnie importowany obiekt `scala.Predef` deklaruje kilka predefiniowanych ty Przykładowo, kiedy wywołujemy metodę Javy, która wymaga typu `java.lang.Integer`, dopuszczalne jest przekazanie typu `scala.Int`. Dzieje się tak ponieważ `Predef` definiuje poniższe konwersje niejawne: -```tut +```scala mdoc import scala.language.implicitConversions implicit def int2Integer(x: Int) = diff --git a/_pl/tour/implicit-parameters.md b/_pl/tour/implicit-parameters.md index ff9aa761b9..2ce27415ea 100644 --- a/_pl/tour/implicit-parameters.md +++ b/_pl/tour/implicit-parameters.md @@ -18,7 +18,7 @@ Argumenty, które mogą być przekazywane jako parametry domniemane, można podz W poniższym przykładzie zdefiniujemy metodę `sum`, która oblicza sumę listy elementów wykorzystując operacje `add` i `unit` obiektu `Monoid`. Należy dodać, że wartości domniemane nie mogą być zdefiniowane globalnie, tylko muszą być elementem pewnego modułu. -```tut +```scala mdoc /** Ten przykład wykorzystuje strukturę z algebry abstrakcyjnej aby zilustrować działanie parametrów domniemanych. Półgrupa jest strukturą algebraiczną na zbiorze A z łączną operacją (czyli taką, która spełnia warunek: add(x, add(y, z)) == add(add(x, y), z)) nazwaną add, która łączy parę obiektów A by zwrócić inny obiekt A. */ abstract class SemiGroup[A] { def add(x: A, y: A): A diff --git a/_pl/tour/inner-classes.md b/_pl/tour/inner-classes.md index 3635d7cccb..2f3fef4ea1 100644 --- a/_pl/tour/inner-classes.md +++ b/_pl/tour/inner-classes.md @@ -11,7 +11,7 @@ previous-page: lower-type-bounds W Scali możliwe jest zdefiniowanie klasy jako element innej klasy. W przeciwieństwie do języków takich jak Java, gdzie tego typu wewnętrzne klasy są elementami ujmujących ich klas, w Scali są one związane z zewnętrznym obiektem. Aby zademonstrować tę różnicę, stworzymy teraz prostą implementację grafu: -```tut +```scala mdoc class Graph { class Node { var connectedNodes: List[Node] = Nil @@ -32,7 +32,7 @@ class Graph { W naszym programie grafy są reprezentowane przez listę wierzchołków. Wierzchołki są obiektami klasy wewnętrznej `Node`. Każdy wierzchołek zawiera listę sąsiadów, które są przechowywane w liście `connectedNodes`. Możemy teraz skonfigurować graf z kilkoma wierzchołkami i połączyć je ze sobą: -```tut +```scala mdoc object GraphTest extends App { val g = new Graph val n1 = g.newNode @@ -45,7 +45,7 @@ object GraphTest extends App { Teraz wzbogacimy nasz przykład o jawne typowanie, aby można było zobaczyć powiązanie typów wierzchołków z grafem: -```tut +```scala mdoc:nest object GraphTest extends App { val g: Graph = new Graph val n1: g.Node = g.newNode @@ -60,7 +60,7 @@ Ten kod pokazuje, że typ wierzchołka jest prefiksowany przez swoją zewnętrzn Przykład niedopuszczalnego programu: -```tut:fail +```scala mdoc:fail object IllegalGraphTest extends App { val g: Graph = new Graph val n1: g.Node = g.newNode @@ -74,7 +74,7 @@ object IllegalGraphTest extends App { Warto zwrócić uwagę na to, że ostatnia linia poprzedniego przykładu byłaby poprawnym programem w Javie. Dla wierzchołków obu grafów Java przypisałaby ten sam typ `Graph.Node`. W Scali także istnieje możliwość wyrażenia takiego typu, zapisując go w formie: `Graph#Node`. Jeżeli byśmy chcieli połączyć wierzchołki różnych grafów, musielibyśmy wtedy zmienić definicję implementacji naszego grafu w następujący sposób: -```tut +```scala mdoc:nest class Graph { class Node { var connectedNodes: List[Graph#Node] = Nil diff --git a/_pl/tour/lower-type-bounds.md b/_pl/tour/lower-type-bounds.md index 093f66214f..c1a166b414 100644 --- a/_pl/tour/lower-type-bounds.md +++ b/_pl/tour/lower-type-bounds.md @@ -13,7 +13,7 @@ Podczas gdy [górne ograniczenia typów](upper-type-bounds.html) zawężają typ Oto przykład, w którym jest to użyteczne: -```tut +```scala mdoc case class ListNode[T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t @@ -24,13 +24,13 @@ case class ListNode[T](h: T, t: ListNode[T]) { Powyższy program implementuje listę jednokierunkową z operacją dodania elementu na jej początek. Niestety typ ten jest niezmienny według parametru typu klasy `ListNode`, tzn. `ListNode[String]` nie jest podtypem `ListNode[Any]`. Z pomocą [adnotacji wariancji](variances.html) możemy wyrazić semantykę podtypowania: -``` +```scala case class ListNode[+T](h: T, t: ListNode[T]) { ... } ``` Niestety ten program się nie skompiluje, ponieważ adnotacja kowariancji może być zastosowana tylko, jeżeli zmienna typu jest używana wyłącznie w pozycji kowariantnej. Jako że zmienna typu `T` występuje jako parametr typu metody `prepend`, ta zasada jest złamana. Z pomocą *dolnego ograniczenia typu* możemy jednak zaimplementować tą metodę w taki sposób, że `T` występuje tylko w pozycji kowariantnej: -```tut +```scala mdoc:nest case class ListNode[+T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t @@ -43,7 +43,7 @@ _Uwaga:_ nowa wersja metody `prepend` ma mniej ograniczający typ. Przykładowo Przykład, który to ilustruje: -```tut +```scala mdoc:fail object LowerBoundTest extends App { val empty: ListNode[Null] = ListNode(null, null) val strList: ListNode[String] = empty.prepend("hello") diff --git a/_pl/tour/mixin-class-composition.md b/_pl/tour/mixin-class-composition.md index 5dcff46652..dc7ad8dc4e 100644 --- a/_pl/tour/mixin-class-composition.md +++ b/_pl/tour/mixin-class-composition.md @@ -12,7 +12,7 @@ previous-page: tuples Domieszka (ang. mixin) to cecha (trait), która używana jest do komponowania klas. {% scalafiddle %} -```tut +```scala mdoc abstract class A { val message: String } @@ -36,7 +36,7 @@ Domieszki i nadklasy mogą posiadać tą samą nadklasę (typ bazowy). Spójrzmy teraz na trochę ciekawszy przykład zawierający klasę abstrakcyjną. -```tut +```scala mdoc abstract class AbsIterator { type T def hasNext: Boolean @@ -46,7 +46,7 @@ abstract class AbsIterator { Klasa ta zawiera abstrakcyjny typ `type T` oraz standardowe metody iteracyjne `hasNext` i `next`. -```tut +```scala mdoc class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 @@ -63,7 +63,7 @@ Klasa `StringIterator` przyjmuje parametr typu `String`, może być ona użyta d Stwórzmy teraz cechę, która również rozszerza `AbsIterator`. -```tut +```scala mdoc trait RichIterator extends AbsIterator { def foreach(f: T => Unit): Unit = while (hasNext) f(next()) } @@ -74,7 +74,7 @@ Ponieważ `RichIterator` jest cechą, nie musi implementować abstrakcyjnych sk Spróbujmy teraz połączyć funkcjonalności `StringIterator` oraz `RichIterator` w jednej klasie. -```tut +```scala mdoc object StringIteratorTest extends App { class RichStringIter extends StringIterator("Scala") with RichIterator val richStringIter = new RichStringIter diff --git a/_pl/tour/multiple-parameter-lists.md b/_pl/tour/multiple-parameter-lists.md index cae31b0fa2..9bb9e100c5 100644 --- a/_pl/tour/multiple-parameter-lists.md +++ b/_pl/tour/multiple-parameter-lists.md @@ -24,7 +24,7 @@ Poniżej omówiony jest przykład użycia. Zaczynając od początkowej wartości 0, funkcja `foldLeft` stosuje funkcję `(m, n) => m + n` na każdym elemencie listy oraz poprzedniej zakumulowanej wartości. {% scalafiddle %} -```tut +```scala mdoc val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val res = numbers.foldLeft(0)((m, n) => m + n) println(res) // 55 @@ -52,7 +52,7 @@ numbers.foldLeft(0)(_ + _) Powyższe wyrażenie `numbers.foldLeft(0)(_ + _)` pozwala trwale ustawić parametr `z` i przekazywać dalej częściową funkcję (partial function), tak jak pokazano to poniżej: -```tut +```scala mdoc:nest val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val numberFunc = numbers.foldLeft(List[Int]())_ @@ -65,7 +65,7 @@ print(cubes.toString()) // List(1, 8, 27, 64, 125, 216, 343, 512, 729, 1000) Podsumowując, `foldLeft` oraz `foldRight` mogą być używane w dowolnej z poniższych postaci: -```tut +```scala mdoc:nest val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers.foldLeft(0)((sum, item) => sum + item) // postać ogólna diff --git a/_pl/tour/named-arguments.md b/_pl/tour/named-arguments.md index 0e3f4965f9..bf297d982d 100644 --- a/_pl/tour/named-arguments.md +++ b/_pl/tour/named-arguments.md @@ -11,7 +11,7 @@ previous-page: default-parameter-values Wywołując metody i funkcje, możesz użyć nazwy parametru jawnie podczas wywołania: -```tut +```scala mdoc def printName(first:String, last:String) = { println(first + " " + last) } @@ -23,7 +23,7 @@ printName(last = "Smith", first = "John") // Wypisuje "John Smith" Warto zwrócić uwagę na to, że kolejność wyboru parametrów podczas wywołania nie ma znaczenia, dopóki wszystkie parametry są nazwane. Ta funkcjonalność jest dobrze zintegrowana z [domyślnymi wartościami parametrów](default-parameter-values.html): -```tut +```scala mdoc:nest def printName(first: String = "John", last: String = "Smith") = { println(first + " " + last) } diff --git a/_pl/tour/nested-functions.md b/_pl/tour/nested-functions.md index a384b0a449..1531854082 100644 --- a/_pl/tour/nested-functions.md +++ b/_pl/tour/nested-functions.md @@ -13,7 +13,7 @@ Scala pozwala na zagnieżdżanie definicji funkcji. Poniższy obiekt określa funkcję `factorial`, która oblicza silnię dla danej liczby: {% scalafiddle %} -```tut +```scala mdoc def factorial(x: Int): Int = { def fact(x: Int, accumulator: Int): Int = { if (x <= 1) accumulator diff --git a/_pl/tour/operators.md b/_pl/tour/operators.md index bbdacf2cd7..8730570849 100644 --- a/_pl/tour/operators.md +++ b/_pl/tour/operators.md @@ -11,7 +11,7 @@ previous-page: type-inference Każda metoda, która przyjmuje jeden parametr, może być użyta jako *operator infiksowy*. Oto definicja klasy `MyBool` która zawiera metody `and` i `or`: -```tut +```scala mdoc case class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that @@ -21,7 +21,7 @@ case class MyBool(x: Boolean) { Można teraz użyć `and` i `or` jako operatory infiksowe: -```tut +```scala mdoc def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) ``` @@ -30,7 +30,7 @@ Można zauważyć, że dzięki zastosowaniu operatorów infiksowych metoda `xor` Dla porównania, oto kod który nie wykorzystuje operatorów infiksowych: -```tut +```scala mdoc:nest def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate) ``` diff --git a/_pl/tour/packages-and-imports.md b/_pl/tour/packages-and-imports.md index 30702a4850..9bcdb38fc1 100644 --- a/_pl/tour/packages-and-imports.md +++ b/_pl/tour/packages-and-imports.md @@ -74,7 +74,7 @@ import users.{UserPreferences => UPrefs} // zaimportuj i zmień nazwę dla wygo Jedną z różnic w Scali od Javy jest to, że deklarację `import` można umieścić w dowolnym miejscu: -```tut +```scala mdoc def sqrtplus1(x: Int) = { import scala.math.sqrt sqrt(x) + 1.0 diff --git a/_pl/tour/pattern-matching.md b/_pl/tour/pattern-matching.md index 0d9a5dd8fd..3b853bff1b 100644 --- a/_pl/tour/pattern-matching.md +++ b/_pl/tour/pattern-matching.md @@ -11,7 +11,7 @@ previous-page: case-classes Scala posiada wbudowany mechanizm dopasowania wzorców. Umożliwia on dopasowanie dowolnego rodzaju danych, przy czym zawsze zwracamy pierwsze dopasowanie. Przykład dopasowania liczby całkowitej: -```tut +```scala mdoc object MatchTest1 extends App { def matchTest(x: Int): String = x match { case 1 => "one" @@ -26,7 +26,7 @@ Blok kodu z wyrażeniami `case` definiuje funkcję, która przekształca liczby Wzorce można także dopasowywać do różnych typów wartości: -```tut +```scala mdoc object MatchTest2 extends App { def matchTest(x: Any): Any = x match { case 1 => "one" diff --git a/_pl/tour/polymorphic-methods.md b/_pl/tour/polymorphic-methods.md index 55b16d0023..113887aeee 100644 --- a/_pl/tour/polymorphic-methods.md +++ b/_pl/tour/polymorphic-methods.md @@ -13,7 +13,7 @@ Metody w Scali mogą być parametryzowane zarówno przez wartości, jak i typy. Przykład poniżej: -```tut +```scala mdoc def dup[T](x: T, n: Int): List[T] = { if (n == 0) Nil diff --git a/_pl/tour/regular-expression-patterns.md b/_pl/tour/regular-expression-patterns.md index 22701d0644..9d8efe1cba 100644 --- a/_pl/tour/regular-expression-patterns.md +++ b/_pl/tour/regular-expression-patterns.md @@ -20,7 +20,7 @@ Elem(prefix:String, label:String, attrs:MetaData, scp:NamespaceBinding, children W tych przypadkach Scala pozwala wzorcom na zastosowanie symbolu `_*` w ostatniej pozycji, aby dopasować sekwencje dowolnej długości. Poniższy przykład demonstruje dopasowanie wzorca, który rozpoznaje początek sekwencji i wiąże resztę do zmiennej `rest`: -```tut +```scala mdoc object RegExpTest1 extends App { def containsScala(x: String): Boolean = { val z: Seq[Char] = x diff --git a/_pl/tour/self-types.md b/_pl/tour/self-types.md index 2c9008a83d..1bbb74be98 100644 --- a/_pl/tour/self-types.md +++ b/_pl/tour/self-types.md @@ -13,7 +13,7 @@ Dążąc do tego, aby nasze oprogramowanie było rozszerzalne, często przydatne Oto definicja opisująca grafy: -```tut +```scala mdoc abstract class Graph { type Edge type Node <: NodeIntf @@ -30,7 +30,7 @@ Grafy składają się z listy węzłów oraz krawędzi, gdzie zarówno typ węz Przykład implementacji klasy `Graph`: -```tut:fail +```scala mdoc:fail abstract class DirectedGraph extends Graph { type Edge <: EdgeImpl class EdgeImpl(origin: Node, dest: Node) { @@ -64,7 +64,7 @@ Jeżeli przyjrzymy się bliżej implementacji metody `connectWith`, możemy dost Scala rozwiązuje ten problem pozwalając na powiązanie klasy z innym typem poprzez jawne typowanie samoreferencji. Możemy użyć tego mechanizmu, aby naprawić powyższy kod: -```tut +```scala mdoc abstract class DirectedGraph extends Graph { type Edge <: EdgeImpl class EdgeImpl(origin: Node, dest: Node) { @@ -95,7 +95,7 @@ W nowej definicji klasy `NodeImpl` referencja `this` jest typu `Node`. Ponieważ Oto konkretna specjalizacja `DirectedGraph`, gdzie abstrakcyjne elementy klasy mają ustalone ścisłe znaczenie: -```tut +```scala mdoc class ConcreteDirectedGraph extends DirectedGraph { type Edge = EdgeImpl type Node = NodeImpl @@ -109,7 +109,7 @@ Należy dodać, że w tej klasie możemy utworzyć `NodeImpl`, ponieważ wiemy j Poniżej przykład zastosowania klasy `ConcreteDirectedGraph`: -```tut +```scala mdoc object GraphTest extends App { val g: Graph = new ConcreteDirectedGraph val n1 = g.addNode diff --git a/_pl/tour/singleton-objects.md b/_pl/tour/singleton-objects.md index c248da92a6..14529d8993 100644 --- a/_pl/tour/singleton-objects.md +++ b/_pl/tour/singleton-objects.md @@ -31,7 +31,7 @@ Duża część obiektów singleton nie istnieje samodzielnie, ale jest powiązan Klasa i jej obiekt towarzyszący mogą być zdefiniowane tylko w tym samym pliku, przykład: -```tut +```scala mdoc class IntPair(val x: Int, val y: Int) object IntPair { diff --git a/_pl/tour/traits.md b/_pl/tour/traits.md index 032423ea0a..4751e0824d 100644 --- a/_pl/tour/traits.md +++ b/_pl/tour/traits.md @@ -18,13 +18,13 @@ Z tego powodu cechy nie przyjmują parametrów wartości. Minimalna definicja cechy składa się ze słowa kluczowego `trait` oraz identyfikatora. -```tut +```scala mdoc trait HairColor ``` Cechy są szczególnie przydatne jako generyczne typy zawierające abstrakcyjne metody. -```tut +```scala mdoc trait Iterator[A] { def hasNext: Boolean def next(): A @@ -39,7 +39,7 @@ Aby rozszerzyć cechę należy użyć słowa kluczowego `extends`. Następnie wymagane jest zaimplementowanie abstrakcyjnych składników danej cechy używając słowa kluczowego `override.` {% scalafiddle %} -```tut +```scala mdoc:nest trait Iterator[A] { def hasNext: Boolean def next(): A @@ -70,7 +70,7 @@ Klasa `IntIterator` przyjmuje parametr `to` (do) jako ograniczenie górne, oraz Jeżeli w jakimś miejscu wymagana jest cecha pewnego typu, to zamiast niej można użyć jej podtypu. {% scalafiddle %} -```tut +```scala mdoc import scala.collection.mutable.ArrayBuffer trait Pet { diff --git a/_pl/tour/tuples.md b/_pl/tour/tuples.md index 9973e42e20..b415c1a348 100644 --- a/_pl/tour/tuples.md +++ b/_pl/tour/tuples.md @@ -17,7 +17,7 @@ Krotki przydają się, gdy chcemy, żeby funkcja zwróciła jednocześnie wiele Krotki tworzy się w następujący sposób: -```tut +```scala mdoc val ingredient = ("Sugar" , 25): Tuple2[String, Int] ``` @@ -32,7 +32,7 @@ W ww. przykładzie jest to `Tuple2[String, Int]`. Krotka zapewnia dostęp do swoich elementów z użyciem składni podkreślnika (underscore). `tuple._n` odwołuje się do n-tego elementu w kolejności (pod warunkiem, że dana krotka zawiera tyle elementów). -```tut +```scala mdoc println(ingredient._1) // wyświetli Sugar println(ingredient._2) // wyświetli 25 @@ -42,7 +42,7 @@ println(ingredient._2) // wyświetli 25 Krotki w Scali wspierają dekonstrukcję -```tut +```scala mdoc val (name, quantity) = ingredient println(name) // wyświetli Sugar @@ -53,7 +53,7 @@ println(quantity) // wyświetli 25 Dekonstrukcja krotek może być bardzo przydatna w dopasowywaniu wzorców (ang. pattern matching) {% scalafiddle %} -```tut +```scala mdoc val planetDistanceFromSun = List( ("Mercury", 57.9), ("Venus", 108.2), @@ -74,7 +74,7 @@ planetDistanceFromSun.foreach { Ma ona też zastosowanie w wyrażeniach 'for'. {% scalafiddle %} -```tut +```scala mdoc val numPairs = List((2, 5), (3, -7), (20, 56)) for ((a, b) <- numPairs) { diff --git a/_pl/tour/type-inference.md b/_pl/tour/type-inference.md index 4c5435eb63..f7f0d42055 100644 --- a/_pl/tour/type-inference.md +++ b/_pl/tour/type-inference.md @@ -13,7 +13,7 @@ Scala posiada wbudowany mechanizm inferencji typów, który pozwala programiści Oto przykład: -```tut +```scala mdoc object InferenceTest1 extends App { val x = 1 + 2 * 3 // typem x jest Int val y = x.toString() // typem y jest String @@ -23,7 +23,7 @@ object InferenceTest1 extends App { Dla metod rekurencyjnych kompilator nie jest w stanie określić zwracanego typu. Oto przykład programu, który zakończy się niepowodzeniem kompilacji z tego powodu: -```tut:fail +```scala mdoc:fail object InferenceTest2 { def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) } @@ -51,7 +51,7 @@ val y: Int = id[Int](1) W niektórych sytuacjach poleganie na inferencji typów w Scali może być niebezpieczne, tak jak demonstruje to poniższy program: -```tut:fail +```scala mdoc:fail object InferenceTest4 { var obj = null obj = new Object() diff --git a/_pl/tour/unified-types.md b/_pl/tour/unified-types.md index c58618a781..e93d2e893b 100644 --- a/_pl/tour/unified-types.md +++ b/_pl/tour/unified-types.md @@ -36,7 +36,7 @@ Jeżeli Scala użyta jest w kontekście środowiska uruchomieniowego Javy, to `A Poniższy przykład pokazuje, że łańcuchy znakowe, liczby całkowite, znaki, wartości logiczne oraz funkcje są obiektami tak samo jak każdy inny obiekt: {% scalafiddle %} -```tut +```scala mdoc val list: List[Any] = List( "Łancuch znaków", 732, // liczba całkowita @@ -70,7 +70,7 @@ Typy wartości mogą być rzutowane w następujący sposób: Dla przykładu: -```tut +```scala mdoc val x: Long = 987654321 val y: Float = x // 9.8765434E8 (w tym wypadku tracimy część precyzji) diff --git a/_pl/tour/upper-type-bounds.md b/_pl/tour/upper-type-bounds.md index 1792e9e3b1..e9e801cd66 100644 --- a/_pl/tour/upper-type-bounds.md +++ b/_pl/tour/upper-type-bounds.md @@ -13,7 +13,7 @@ W Scali [parametry typów](generic-classes.html) oraz [typy abstrakcyjne](abstra Poniższy przykład demonstruje zastosowanie ograniczeń górnych typu dla parametru typu klasy `Cage`: -```tut +```scala mdoc abstract class Animal { def name: String } diff --git a/_pl/tour/variances.md b/_pl/tour/variances.md index 2efc1a7638..db0e485413 100644 --- a/_pl/tour/variances.md +++ b/_pl/tour/variances.md @@ -13,7 +13,7 @@ Scala wspiera adnotacje wariancji parametrów typów [klas generycznych](generic Na stronie o [klasach generycznych](generic-classes.html) omówiliśmy przykład zmiennego stosu. Wyjaśniliśmy, że typ definiowany przez klasę `Stack[T]` jest poddany niezmiennemu podtypowaniu w stosunku do parametru typu. Może to ograniczyć możliwość ponownego wykorzystania abstrakcji tej klasy. Spróbujemy teraz opracować funkcyjną (tzn. niemutowalną) implementację dla stosów, które nie posiadają tego ograniczenia. Warto zwrócić uwagę, że jest to zaawansowany przykład łączący w sobie zastosowanie [funkcji polimorficznych](polymorphic-methods.html), [dolnych ograniczeń typu](lower-type-bounds.html) oraz kowariantnych adnotacji parametru typu. Dodatkowo stosujemy też [klasy wewnętrzne](inner-classes.html), aby połączyć ze sobą elementy stosu bez jawnych powiązań. -```tut +```scala mdoc class Stack[+T] { def push[S >: T](elem: S): Stack[S] = new Stack[S] { override def top: S = elem diff --git a/_plugins/mdoc_replace.rb b/_plugins/mdoc_replace.rb new file mode 100644 index 0000000000..0b62828227 --- /dev/null +++ b/_plugins/mdoc_replace.rb @@ -0,0 +1,22 @@ +module Jekyll + class MdocConverter < Converter + safe false + priority :high + + def matches(ext) + ext =~ /^\.(md|markdown)$/i + end + + def output_ext(ext) + ".html" + end + + def convert(content) + content = content.gsub("```scala mdoc:fail\n", "```scala\n") + content = content.gsub("```scala mdoc:crash\n", "```scala\n") + content = content.gsub("```scala mdoc:nest\n", "```scala\n") + content = content.gsub("```scala mdoc:reset\n", "```scala\n") + content.gsub("```scala mdoc\n", "```scala\n") + end + end +end diff --git a/_plugins/tut_replace.rb b/_plugins/tut_replace.rb deleted file mode 100644 index 06ee3c7fe9..0000000000 --- a/_plugins/tut_replace.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Jekyll - class TutConverter < Converter - safe false - priority :high - - def matches(ext) - ext =~ /^\.(md|markdown)$/i - end - - def output_ext(ext) - ".html" - end - - def convert(content) - content = content.gsub("```tut:fail\n", "```scala\n") - content = content.gsub("```tut:nofail\n", "```scala\n") - content.gsub("```tut\n", "```scala\n") - end - end -end diff --git a/_pt-br/tour/abstract-type-members.md b/_pt-br/tour/abstract-type-members.md index 4bca7396dc..8a798f4468 100644 --- a/_pt-br/tour/abstract-type-members.md +++ b/_pt-br/tour/abstract-type-members.md @@ -13,7 +13,7 @@ Em Scala, as classes são parametrizadas com valores (os parâmetros de construt Aqui está um exemplo que mostra uma definição de valor diferido e uma definição de tipo abstrato como membros de uma [trait](traits.html) chamada `Buffer`. -```tut +```scala mdoc trait Buffer { type T val element: T @@ -24,7 +24,7 @@ trait Buffer { No seguinte programa temos uma classe `SeqBuffer` que nos permite armazenar apenas as sequências no buffer ao definir que o tipo `T` precisa ser um subtipo de `Seq[U]` para um novo tipo abstrato `U`: -```tut +```scala mdoc abstract class SeqBuffer extends Buffer { type U type T <: Seq[U] @@ -34,7 +34,7 @@ abstract class SeqBuffer extends Buffer { [Traits](traits.html) ou [classes](classes.html) com membros de tipo abstratos são frequentemente utilizadas em combinação com instâncias de classe anônimas. Para ilustrar isso, agora analisamos um programa que lida com um buffer de sequência que se refere a uma lista de inteiros: -```tut +```scala mdoc abstract class IntSeqBuffer extends SeqBuffer { type U = Int } @@ -55,22 +55,20 @@ O tipo de retorno do método `newIntSeqBuf` refere-se a uma especialização da Observe que muitas vezes é possível transformar os membros de tipo abstrato em parâmetros de tipo de classes e vice-versa. Aqui está uma versão do código acima que usa apenas parâmetros de tipo: -```tut +```scala mdoc:nest abstract class Buffer[+T] { val element: T } abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] { def length = element.length } -object AbstractTypeTest2 extends App { - def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] = - new SeqBuffer[Int, List[Int]] { - val element = List(e1, e2) - } - val buf = newIntSeqBuf(7, 8) - println("length = " + buf.length) - println("content = " + buf.element) -} +def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] = + new SeqBuffer[Int, List[Int]] { + val element = List(e1, e2) + } +val buf = newIntSeqBuf(7, 8) +println("length = " + buf.length) +println("content = " + buf.element) ``` Note que temos que usar [anotação de variância](variances.html) aqui; Caso contrário, não seríamos capazes de ocultar o tipo implementado pela sequência concreta do objeto retornado pelo método `newIntSeqBuf`. Além disso, há casos em que não é possível substituir tipos abstratos com parâmetros de tipo. diff --git a/_pt-br/tour/automatic-closures.md b/_pt-br/tour/automatic-closures.md index a16bec7160..2f9072a59d 100644 --- a/_pt-br/tour/automatic-closures.md +++ b/_pt-br/tour/automatic-closures.md @@ -15,7 +15,7 @@ Scala permite funções sem parâmetros como parâmetros de métodos. Quando um O código a seguir demonstra esse mecanismo: -```tut +```scala mdoc object TargetTest1 extends App { def whileLoop(cond: => Boolean)(body: => Unit): Unit = if (cond) { @@ -36,7 +36,7 @@ Podemos combinar o uso de [operadores infix/postfix](operators.html) com este me Aqui está a implementação de uma instrução que executa loop a menos que uma condição seja satisfeita: -```tut +```scala mdoc object TargetTest2 extends App { def loop(body: => Unit): LoopUnlessCond = new LoopUnlessCond(body) diff --git a/_pt-br/tour/case-classes.md b/_pt-br/tour/case-classes.md index 16886891e3..5524865ee6 100644 --- a/_pt-br/tour/case-classes.md +++ b/_pt-br/tour/case-classes.md @@ -18,7 +18,7 @@ Scala suporta o conceito de _classes case_. Classes case são classes regulares Aqui temos um exemplo de hierarquia de tipos para *Notification* que consiste em uma super classe abstrata `Notification` e três tipos concretos de notificação implementados com classes case `Email`, `SMS`, e `VoiceRecording`. -```tut +```scala mdoc abstract class Notification case class Email(sourceEmail: String, title: String, body: String) extends Notification case class SMS(sourceNumber: String, message: String) extends Notification @@ -27,26 +27,26 @@ case class VoiceRecording(contactName: String, link: String) extends Notificatio Instânciar uma classe case é fácil: (Perceba que nós não precisamos da palavra-chave `new`) -```tut +```scala mdoc val emailDeJohn = Email("john.doe@mail.com", "Saudações do John!", "Olá Mundo") ``` Os parâmetros do construtor de uma classe case são tratados como valores públicos e podem ser acessados diretamente. -```tut +```scala mdoc val titulo = emailDeJohn.title println(titulo) // prints "Saudações do John!" ``` Com classes case, você não pode alterar seus campos diretamente. (ao menos que você declare `var` antes de um campo, mas fazê-lo geralmente é desencorajado). -```tut:fail +```scala mdoc:fail emailDeJohn.title = "Adeus do John!" // Erro the compilação. Não podemos atribuir outro valor para um campo que foi declarado como val, lembrando que todos os campos de classes case são val por padrão. ``` Ao invés disso, faça uma cópia utilizando o método `copy`. Como descrito abaixo, então você poderá substituir alguns dos campos: -```tut +```scala mdoc val emailEditado = emailDeJohn.copy(title = "Estou aprendendo Scala!", body = "É muito legal!") println(emailDeJohn) // prints "Email(john.doe@mail.com,Saudações do John!,Hello World!)" @@ -55,7 +55,7 @@ println(emailEditado) // prints "Email(john.doe@mail.com,Estou aprendendo Scala, Para cada classe case em Scala o compilador gera um método `equals` que implementa a igualdade estrutural e um método `toString`. Por exemplo: -```tut +```scala mdoc val primeiroSMS = SMS("12345", "Hello!") val segundoSMS = SMS("12345", "Hello!") @@ -75,7 +75,7 @@ SMS é: SMS(12345, Hello!) Com classes case, você pode utilizar **correspondência de padrões** para manipular seus dados. Aqui temos um exemplo de uma função que escreve como saída diferente mensagens dependendo do tipo de notificação recebida: -```tut +```scala mdoc def mostrarNotificacao(notificacao: Notification): String = { notificacao match { case Email(email, title, _) => @@ -96,7 +96,7 @@ println(mostrarNotificacao(algumaMsgVoz)) // Saída "Você recebeu uma Mensagem Aqui um exemplo mais elaborado utilizando a proteção `if`. Com a proteção `if`, o correspondência de padrão irá falhar se a condição de proteção retorna falso. -```tut +```scala mdoc:nest def mostrarNotificacaoEspecial(notificacao: Notification, emailEspecial: String, numeroEspecial: String): String = { notificacao match { case Email(email, _, _) if email == emailEspecial => diff --git a/_pt-br/tour/classes.md b/_pt-br/tour/classes.md index 9861271a36..26a49fc55e 100644 --- a/_pt-br/tour/classes.md +++ b/_pt-br/tour/classes.md @@ -12,7 +12,7 @@ language: pt-br Classes em Scala são templates estáticos que podem ser instanciados como vários objetos em tempo de execução. Aqui uma definição de classe que define a classe `Ponto`: -```tut +```scala mdoc class Ponto(var x: Int, var y: Int) { def move(dx: Int, dy: Int): Unit = { x = x + dx @@ -31,7 +31,7 @@ Perceba que em Scala, não é necessário declarar `return` para então retornar Classes são instânciadas com a primitiva `new`, por exemplo: -```tut +```scala mdoc object Classes { def main(args: Array[String]) { val pt = new Ponto(1, 2) diff --git a/_pt-br/tour/compound-types.md b/_pt-br/tour/compound-types.md index d648fa319a..7465bdebb4 100644 --- a/_pt-br/tour/compound-types.md +++ b/_pt-br/tour/compound-types.md @@ -13,7 +13,7 @@ language: pt-br Suponha que temos duas traits `Cloneable` and `Resetable`: -```tut +```scala mdoc trait Cloneable extends java.lang.Cloneable { override def clone(): Cloneable = { super.clone().asInstanceOf[Cloneable] diff --git a/_pt-br/tour/default-parameter-values.md b/_pt-br/tour/default-parameter-values.md index 898eca8b0d..197ca5c058 100644 --- a/_pt-br/tour/default-parameter-values.md +++ b/_pt-br/tour/default-parameter-values.md @@ -50,7 +50,7 @@ Enquanto isso nos impede de nos repetir, é menos do que expressivo. Scala adiciona suporte direto para isso: -```tut +```scala mdoc class HashMap[K,V](initialCapacity:Int = 16, loadFactor:Float = 0.75f) { } diff --git a/_pt-br/tour/extractor-objects.md b/_pt-br/tour/extractor-objects.md index 9dd9e21e11..e91788ee9f 100644 --- a/_pt-br/tour/extractor-objects.md +++ b/_pt-br/tour/extractor-objects.md @@ -11,7 +11,7 @@ language: pt-br Em Scala, padrões podem ser definidos independentemente de classes case. Para este fim, um método chamado `unapply` é definido para retornar um extrator. Um extrator pode ser pensado como um método especial que inverte o efeito da aplicação de um determinado objeto em algumas entradas. Seu objetivo é "extrair" as entradas que estavam presentes antes da operação `apply`. Por exemplo, o código a seguir define um [objeto](singleton-objects.html) extrator chamado Twice. -```tut +```scala mdoc object Twice { def apply(x: Int): Int = x * 2 def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None diff --git a/_pt-br/tour/generic-classes.md b/_pt-br/tour/generic-classes.md index 82234c4636..d6e72103a0 100644 --- a/_pt-br/tour/generic-classes.md +++ b/_pt-br/tour/generic-classes.md @@ -12,7 +12,7 @@ language: pt-br Semelhante ao Java 5 (aka. JDK 1.5), Scala tem suporte nativo para classes parametrizadas com tipos. Essas classes genéricas são particularmente úteis para o desenvolvimento de classes que representam coleções de dados. Aqui temos um exemplo que demonstra isso: -```tut +```scala mdoc class Stack[T] { var elems: List[T] = Nil def push(x: T) { elems = x :: elems } @@ -25,7 +25,7 @@ A classe `Stack` modela uma pilha mutável que contém elementos de um tipo arbi Aqui temos mais alguns exemplos de uso: -```tut +```scala mdoc object GenericsTest extends App { val stack = new Stack[Int] stack.push(1) diff --git a/_pt-br/tour/higher-order-functions.md b/_pt-br/tour/higher-order-functions.md index eaba32861c..f71baf9e67 100644 --- a/_pt-br/tour/higher-order-functions.md +++ b/_pt-br/tour/higher-order-functions.md @@ -11,7 +11,7 @@ language: pt-br Scala permite definir funções de ordem superior. Tais funções _recebem outras funções como parâmetros_, ou _resultam em uma função_. Por exemplo, a função `apply` recebe outra função `f` e um valor `v` então aplica a função `f` em`v`: -```tut +```scala mdoc def apply(f: Int => String, v: Int) = f(v) ``` @@ -19,13 +19,13 @@ _Nota: métodos são automaticamente convertidos em funções se o contexto dema Outro exemplo: -```tut +```scala mdoc class Decorator(left: String, right: String) { def layout[A](x: A) = left + x.toString() + right } object FunTest extends App { - def apply(f: Int => String, v: Int) = f(v) + override def apply(f: Int => String, v: Int) = f(v) val decorator = new Decorator("[", "]") println(apply(decorator.layout, 7)) } diff --git a/_pt-br/tour/implicit-conversions.md b/_pt-br/tour/implicit-conversions.md index c8ee38d23b..cc96f99062 100644 --- a/_pt-br/tour/implicit-conversions.md +++ b/_pt-br/tour/implicit-conversions.md @@ -41,7 +41,7 @@ O objeto implicitamente importado `scala.Predef` declara vários tipos predefini Por exemplo, ao chamar um método Java que espera um `java.lang.Integer`, você está livre para passar um `scala.Int` em vez disso. Isso ocorre porque `Predef` inclui as seguintes conversões implícitas: -```tut +```scala mdoc import scala.language.implicitConversions implicit def int2Integer(x: Int) = diff --git a/_pt-br/tour/implicit-parameters.md b/_pt-br/tour/implicit-parameters.md index e963c4b9e3..7f1f0d0a98 100644 --- a/_pt-br/tour/implicit-parameters.md +++ b/_pt-br/tour/implicit-parameters.md @@ -19,7 +19,7 @@ Os argumentos reais que são elegíveis para serem passados para um parâmetro i No exemplo a seguir, definimos um método `sum` que calcula a soma de uma lista de elementos usando as operações `add` e `unit` do monoide. Observe que valores implícitos não podem ser *top-level*, eles precisam ser membros de um modelo. -```tut +```scala mdoc /** Este exemplo usa uma estrutura da álgebra abstrata para mostrar como funcionam os parâmetros implícitos. Um semigrupo é uma estrutura algébrica em um conjunto A com uma operação (associativa), chamada add, que combina um par de A's e retorna um outro A. */ abstract class SemiGroup[A] { def add(x: A, y: A): A diff --git a/_pt-br/tour/inner-classes.md b/_pt-br/tour/inner-classes.md index dbcbe4c93e..aff2633035 100644 --- a/_pt-br/tour/inner-classes.md +++ b/_pt-br/tour/inner-classes.md @@ -11,7 +11,7 @@ language: pt-br Em Scala é possível declarar classes que tenham outras classes como membros. Em contraste com a linguagenm Java, onde classes internas são membros da classe em que foram declaradas, em Scala as classes internas são ligadas ao objeto exterior. Para ilustrar essa diferença, rapidamente esboçamos a implementação de grafo como um tipo de dados: -```tut +```scala mdoc class Graph { class Node { var connectedNodes: List[Node] = Nil @@ -32,7 +32,7 @@ class Graph { Em nosso programa, os grafos são representados por uma lista de nós. Os nós são objetos da classe interna `Node`. Cada nó tem uma lista de vizinhos, que são armazenados na lista `connectedNodes`. Agora podemos configurar um grafo com alguns nós e conectar os nós de forma incremental: -```tut +```scala mdoc object GraphTest extends App { val g = new Graph val n1 = g.newNode @@ -45,7 +45,7 @@ object GraphTest extends App { Agora melhoramos o exemplo acima com tipos, para assim declarar explicitamente qual o tipo das várias entidades definidas: -```tut +```scala mdoc:nest object GraphTest extends App { val g: Graph = new Graph val n1: g.Node = g.newNode @@ -59,7 +59,7 @@ object GraphTest extends App { Este código mostra claramente que o tipo nó é prefixado com sua instância externa (em nosso exemplo é o objeto `g`). Se agora temos dois grafos, o sistema de tipos de Scala não nos permite misturar nós definidos dentro de um grafo com os nós de outro, já que os nós do outro grafo têm um tipo diferente. Aqui está um programa inválido: -```tut:fail +```scala mdoc:fail object IllegalGraphTest extends App { val g: Graph = new Graph val n1: g.Node = g.newNode @@ -73,7 +73,7 @@ object IllegalGraphTest extends App { Observe que em Java a última linha no programa do exemplo anterior é válida. Para nós de ambos os grafos, Java atribuiria o mesmo tipo `Graph.Node`; isto é, `Node` é prefixado com a classe `Graph`. Em Scala, esse tipo também pode ser expresso, e é escrito `Graph#Node`. Se quisermos ser capazes de conectar nós de diferentes grafos, temos que mudar a definição inicial da nossa implementação do grafo da seguinte maneira: -```tut +```scala mdoc:nest class Graph { class Node { var connectedNodes: List[Graph#Node] = Nil diff --git a/_pt-br/tour/lower-type-bounds.md b/_pt-br/tour/lower-type-bounds.md index 7e89933be2..61e5553ec7 100644 --- a/_pt-br/tour/lower-type-bounds.md +++ b/_pt-br/tour/lower-type-bounds.md @@ -13,7 +13,7 @@ Enquanto o [limitante superior de tipos](upper-type-bounds.html) limita um tipo Aqui está um exemplo onde isso é útil: -```tut +```scala mdoc case class ListNode[T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t @@ -24,7 +24,7 @@ case class ListNode[T](h: T, t: ListNode[T]) { O programa acima implementa uma linked list com uma operação de pré-inserção. Infelizmente, esse tipo é invariante no parâmetro de tipo da classe `ListNode`; Ou seja, `ListNode [String]` não é um subtipo de `ListNode [Any]`. Com a ajuda de [anotações de variância](variances.html) podemos expressar tal semântica de subtipo: -``` +```scala case class ListNode[+T](h: T, t: ListNode[T]) { ... } ``` @@ -32,7 +32,7 @@ Infelizmente, este programa não compila, porque uma anotação de covariância Aqui está o código correspondente: -```tut +```scala mdoc:reset case class ListNode[+T](h: T, t: ListNode[T]) { def head: T = h def tail: ListNode[T] = t @@ -45,7 +45,7 @@ _Nota:_ o novo método `prepend` tem um tipo ligeiramente menos restritivo. Perm Aqui está o código que ilustra isso: -```tut +```scala object LowerBoundTest extends App { val empty: ListNode[Null] = ListNode(null, null) val strList: ListNode[String] = empty.prepend("hello") diff --git a/_pt-br/tour/mixin-class-composition.md b/_pt-br/tour/mixin-class-composition.md index 2f830f6b8b..80002a731a 100644 --- a/_pt-br/tour/mixin-class-composition.md +++ b/_pt-br/tour/mixin-class-composition.md @@ -12,7 +12,7 @@ _Nota de tradução: A palavra `mixin` pode ser traduzida como mescla, porém é Ao contrário de linguagens que suportam somente _herança simples_, Scala tem uma noção mais abrangente sobre a reutilização de classes. Scala torna possível reutilizar a _nova definição de membros de uma classe_ (por exemplo: o relacionamento delta para com a superclasse) na definição de uma nova classe. Isso é expressado como uma _composição de classe mixin ou mixin-class composition_. Considere a seguinte abstração para iterators. -```tut +```scala mdoc abstract class AbsIterator { type T def hasNext: Boolean @@ -22,7 +22,7 @@ abstract class AbsIterator { A seguir, considere a classe mixin que estende `AbsIterator` com um método `foreach` que aplica uma dada função para cada elemento retornado pelo iterator. Para definir tal classe que será utilizada como um mixin a palavra-chave `trait` deve ser declarada. -```tut +```scala mdoc trait RichIterator extends AbsIterator { def foreach(f: T => Unit) { while (hasNext) f(next()) } } @@ -30,7 +30,7 @@ trait RichIterator extends AbsIterator { Aqui uma classes iterator concreta a qual retorna sucessivos caracteres de uma dada string: -```tut +```scala mdoc class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 @@ -41,7 +41,7 @@ class StringIterator(s: String) extends AbsIterator { Poderíamos combinar a funcionalidade de `StringIterator` e `RichIterator` em uma só classe. Com herança simples e interfaces isso é impossível, pois ambas as classes contém implementações para seus membros. Scala nos ajuda com a sua _composição de classes mixin_. Isso permite que programadores reutilizem o delta de uma definição de uma classe, por exemplo: todas as novas definições não são herdadas. Esse mecanismo torna possível combinar `StringIterator` com `RichIterator`, como pode ser visto no programa teste a seguir, que imprime uma coluna de todos os caracteres de uma dada string. -```tut +```scala mdoc object StringIteratorTest { def main(args: Array[String]) { class Iter extends StringIterator("Scala") with RichIterator diff --git a/_pt-br/tour/multiple-parameter-lists.md b/_pt-br/tour/multiple-parameter-lists.md index 4db4692e7f..8523bc75ba 100644 --- a/_pt-br/tour/multiple-parameter-lists.md +++ b/_pt-br/tour/multiple-parameter-lists.md @@ -15,7 +15,7 @@ Métodos podem definir múltiplas listas de parâmetros. Quando um método é ch Aqui um exemplo: -```tut +```scala mdoc object CurryTest extends App { def filter(xs: List[Int], p: Int => Boolean): List[Int] = diff --git a/_pt-br/tour/named-arguments.md b/_pt-br/tour/named-arguments.md index 008e403cb1..0a32847873 100644 --- a/_pt-br/tour/named-arguments.md +++ b/_pt-br/tour/named-arguments.md @@ -10,7 +10,7 @@ language: pt-br Ao chamar métodos e funções, você pode utilizar explicitamente o nome das variáveis nas chamadas, por exemplo: -```tut +```scala mdoc def imprimeNome(nome:String, sobrenome:String) = { println(nome + " " + sobrenome) } @@ -22,7 +22,7 @@ imprimeNome(sobrenome = "Smith",nome = "John") // Imprime "John Smith" Perceba que a ordem não importa quando você utiliza parâmetros nomeados nas chamadas de métodos e funções, desde que todos os parâmetros sejam declarados. Essa funcionalidade pode ser combinada com [parâmetros com valor padrão](default-parameter-values.html): -```tut +```scala mdoc:nest def imprimeNome(nome:String = "John", sobrenome:String = "Smith") = { println(nome + " " + sobrenome) } diff --git a/_pt-br/tour/nested-functions.md b/_pt-br/tour/nested-functions.md index 03a446be1f..919d6f1253 100644 --- a/_pt-br/tour/nested-functions.md +++ b/_pt-br/tour/nested-functions.md @@ -11,7 +11,7 @@ language: pt-br Em scala é possível aninhar definições de funções. O objeto a seguir fornece uma função `filter` para extrair valores de uma lista de inteiros que são abaixo de um determinado valor: -```tut +```scala mdoc object FilterTest extends App { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = diff --git a/_pt-br/tour/operators.md b/_pt-br/tour/operators.md index a84dea6dce..b38e0e3105 100644 --- a/_pt-br/tour/operators.md +++ b/_pt-br/tour/operators.md @@ -11,7 +11,7 @@ language: pt-br Qualquer método que tenha um único parâmetro pode ser usado como um *operador infix* em Scala. Aqui está a definição da classe `MyBool` que inclui os métodos `add` e `or`: -```tut +```scala mdoc case class MyBool(x: Boolean) { def and(that: MyBool): MyBool = if (x) that else this def or(that: MyBool): MyBool = if (x) this else that @@ -21,7 +21,7 @@ case class MyBool(x: Boolean) { Agora é possível utilizar as funções `and` and `or` como operadores infix: -```tut +```scala mdoc def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y) ``` @@ -30,7 +30,7 @@ Isso ajuda a tornar a definição de `xor` mais legível. Aqui está o código correspondente em uma sintaxe de linguagem de programação orientada a objetos mais tradicional: -```tut +```scala mdoc:nest def not(x: MyBool) = x.negate def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate) ``` diff --git a/_pt-br/tour/pattern-matching.md b/_pt-br/tour/pattern-matching.md index 049776f0a6..1c53b3cd02 100644 --- a/_pt-br/tour/pattern-matching.md +++ b/_pt-br/tour/pattern-matching.md @@ -15,7 +15,7 @@ _Nota de tradução: A palavra cujo o significado melhor corresponde a palavra ` Scala possui mecanismo de correspondência de padrão embutido. Isso permite realizar o match de qualquer tipo de dados com a política de primeiro match. Aqui um pequeno exemplo que mostrar como realizar o match de um número inteiro: -```tut +```scala mdoc object MatchTest1 extends App { def matchTest(x: Int): String = x match { case 1 => "um" @@ -30,7 +30,7 @@ O bloco com a declaração `case` define a função que mapeia inteiros para str Aqui um segundo exemplo no qual o match é realizado em valores de diferentes tipos: -```tut +```scala mdoc object MatchTest2 extends App { def matchTest(x: Any): Any = x match { case 1 => "um" diff --git a/_pt-br/tour/polymorphic-methods.md b/_pt-br/tour/polymorphic-methods.md index a11b599a28..ed0dd535f8 100644 --- a/_pt-br/tour/polymorphic-methods.md +++ b/_pt-br/tour/polymorphic-methods.md @@ -14,7 +14,7 @@ Os métodos em Scala podem ser parametrizados com valores e tipos. Como no níve Por exemplo: -```tut +```scala mdoc def dup[T](x: T, n: Int): List[T] = { if (n == 0) Nil diff --git a/_pt-br/tour/regular-expression-patterns.md b/_pt-br/tour/regular-expression-patterns.md index 470b5bbbe3..9009118fc0 100644 --- a/_pt-br/tour/regular-expression-patterns.md +++ b/_pt-br/tour/regular-expression-patterns.md @@ -20,7 +20,7 @@ Elem(prefix:String, label:String, attrs:MetaData, scp:NamespaceBinding, children Em tais casos, Scala permite que padrões tenham o curinga `_*` na posição mais à direita para ter lugar para sequências arbitrariamente longas. O exemplo a seguir demonstra um padrão que faz o match de um prefixo de uma sequência e vincula o resto à variável `rest`. -```tut +```scala mdoc object RegExpTest1 extends App { def containsScala(x: String): Boolean = { val z: Seq[Char] = x diff --git a/_pt-br/tour/self-types.md b/_pt-br/tour/self-types.md index 764552c329..2596a83223 100644 --- a/_pt-br/tour/self-types.md +++ b/_pt-br/tour/self-types.md @@ -13,7 +13,7 @@ Ao desenvolver um software extensível, às vezes é útil declarar explicitamen Aqui está uma definição que descreve um grafo: -```tut +```scala mdoc abstract class Graph { type Edge type Node <: NodeIntf @@ -30,7 +30,7 @@ Um grafo consiste em uma lista de nós e arestas onde o nó e o tipo de aresta s Uma possível implementação de `Graph` é ilustrada na classe a seguir: -```tut:fail +```scala mdoc:fail abstract class DirectedGraph extends Graph { type Edge <: EdgeImpl class EdgeImpl(origin: Node, dest: Node) { @@ -62,7 +62,7 @@ Em Scala é possível vincular uma classe a outro tipo (que será implementado n Aqui está o programa já corrigido: -```tut +```scala mdoc abstract class DirectedGraph extends Graph { type Edge <: EdgeImpl class EdgeImpl(origin: Node, dest: Node) { @@ -93,7 +93,7 @@ Nesta nova definição de classe `NodeImpl`, `this` tem o tipo `Node`. Como o ti Aqui está uma especialização concreta de `DirectedGraph` onde todos os membros da classe abstrata são definidos: -```tut +```scala mdoc class ConcreteDirectedGraph extends DirectedGraph { type Edge = EdgeImpl type Node = NodeImpl @@ -107,7 +107,7 @@ Observe que nesta classe, podemos instanciar `NodeImpl` porque agora sabemos que Aqui está um exemplo de uso da classe `ConcreteDirectedGraph`: -```tut +```scala mdoc object GraphTest extends App { val g: Graph = new ConcreteDirectedGraph val n1 = g.addNode @@ -117,4 +117,4 @@ object GraphTest extends App { n2.connectWith(n3) n1.connectWith(n3) } -``` \ No newline at end of file +``` diff --git a/_pt-br/tour/singleton-objects.md b/_pt-br/tour/singleton-objects.md index 1f0bdc7e51..850af29abd 100644 --- a/_pt-br/tour/singleton-objects.md +++ b/_pt-br/tour/singleton-objects.md @@ -34,7 +34,7 @@ A maioria dos objetos singleton não estão sozinhos, mas sim associados com uma Se houver um objeto acompanhante para uma classe, ambos devem ser definidos no mesmo aquivo fonte. Por exemplo: -```tut +```scala mdoc class IntPair(val x: Int, val y: Int) object IntPair { diff --git a/_pt-br/tour/traits.md b/_pt-br/tour/traits.md index 261e4ac69d..23bc17e04d 100644 --- a/_pt-br/tour/traits.md +++ b/_pt-br/tour/traits.md @@ -12,7 +12,7 @@ language: pt-br Similar a interfaces em Java, traits são utilizadas para definir tipos de objetos apenas especificando as assinaturas dos métodos suportados. Como em Java 8, Scala permite que traits sejam parcialmente implementadas; ex. é possível definir uma implementação padrão para alguns métodos. Diferentemente de classes, traits não precisam ter construtores com parâmetros. Veja o exemplo a seguir: -```tut +```scala mdoc trait Similaridade { def eSemelhante(x: Any): Boolean def naoESemelhante(x: Any): Boolean = !eSemelhante(x) @@ -21,7 +21,7 @@ trait Similaridade { Tal trait consiste em dois métodos `eSemelhante` e `naoESemelhante`. Equanto `eSemelhante` não fornece um método com implementação concreta (que é semelhante ao abstract na linguagem Java), o método `naoESemelhante` define um implementação concreta. Consequentemente, classes que integram essa trait só precisam fornecer uma implementação concreta para o método `eSemelhante`. O comportamento para `naoESemelhante` é herdado diretamente da trait. Traits são tipicamente integradas a uma [classe](classes.html) (ou outras traits) utilizando a [composição mesclada de classes](mixin-class-composition.html): -```tut +```scala mdoc class Point(xc: Int, yc: Int) extends Similaridade { var x: Int = xc var y: Int = yc diff --git a/_pt-br/tour/tuples.md b/_pt-br/tour/tuples.md index f403e66b2a..4f149a48b7 100644 --- a/_pt-br/tour/tuples.md +++ b/_pt-br/tour/tuples.md @@ -15,7 +15,7 @@ Tuplas são sobretudo úteis para retornar múltiplos valores de um método. Uma Tupla com dois elementos pode ser criada dessa forma: -```tut +```scala mdoc val ingrediente = ("Açucar" , 25) ``` @@ -29,7 +29,7 @@ Para representar tuplas, Scala usa uma serie de classes: `Tuple2`, `Tuple3`, etc Uma maneira de acessar os elementos da tupla é pela sua respectiva posição. Os elementos individuais são nomeados `_1` , `_2` , e assim por diante. -```tut +```scala mdoc println(ingrediente._1) // Açucar println(ingrediente._2) // 25 ``` @@ -38,7 +38,7 @@ println(ingrediente._2) // 25 Uma tupla pode também ser desmembrada usando correspondência de padrões: -```tut +```scala mdoc val (nome, quantidade) = ingrediente println(nome) // Açucar println(quantidade) // 25 @@ -48,7 +48,7 @@ Aqui o tipo inferido para `nome` é `String` e para `quantidade` o tipo inferido Outro exemplo de correspondência de padrões em uma tupla: -```tut +```scala mdoc val planetas = List(("Mercúrio", 57.9), ("Vênus", 108.2), ("Terra", 149.6), ("Marte", 227.9), ("Júpiter", 778.3)) @@ -61,7 +61,7 @@ planetas.foreach{ Ou, um exemplo com `for` : -```tut +```scala mdoc val numPars = List((2, 5), (3, -7), (20, 56)) for ((a, b) <- numPars) { println(a * b) diff --git a/_pt-br/tour/type-inference.md b/_pt-br/tour/type-inference.md index 080eaa85ee..2a32f6d124 100644 --- a/_pt-br/tour/type-inference.md +++ b/_pt-br/tour/type-inference.md @@ -13,7 +13,7 @@ Scala tem um mecanismo nativo de inferência de tipos que permite ao programador Por exemplo: -```tut +```scala mdoc object InferenceTest1 extends App { val x = 1 + 2 * 3 // o tipo de x é Int val y = x.toString() // o tipo de y é String @@ -25,7 +25,7 @@ Para métodos recursivos, o compilador não é capaz de inferir o tipo de retorn Exemplo de um método que não irá compilar por este motivo: -```tut:fail +```scala mdoc:fail object InferenceTest2 { def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) } @@ -54,7 +54,7 @@ val y: Int = id[Int](1) Em algumas situações, pode ser muito perigoso confiar no mecanismo de inferência de tipos de Scala como mostra o seguinte programa: -```tut:fail +```scala mdoc:fail object InferenceTest4 { var obj = null obj = new Object() diff --git a/_pt-br/tour/unified-types.md b/_pt-br/tour/unified-types.md index 092ef6887f..0cb9bb86b6 100644 --- a/_pt-br/tour/unified-types.md +++ b/_pt-br/tour/unified-types.md @@ -19,7 +19,7 @@ A superclass de todas as classes `scala.Any` tem duas subclasses diretas `scala. Observe que o diagrama acima mostra implicitamente as conversões entre as classes de valores. Este exemplo demonstra que números numbers, caracteres, valores booleanos, e funções são objetos como qualquer outro objeto: -```tut +```scala object TiposUnificados extends App { val set = new scala.collection.mutable.LinkedHashSet[Any] set += "Sou uma string" // adiciona uma string ao set diff --git a/_pt-br/tour/upper-type-bounds.md b/_pt-br/tour/upper-type-bounds.md index c001028026..b90a421850 100644 --- a/_pt-br/tour/upper-type-bounds.md +++ b/_pt-br/tour/upper-type-bounds.md @@ -12,7 +12,7 @@ language: pt-br Em Scala, [parâmetros de tipos](generic-classes.html) e [tipos abstratos](abstract-type-members.html) podem ser restringidos por um limitante de tipo. Tal limitante de tipo limita os valores concretos de uma variável de tipo e possivelmente revela mais informações sobre os membros de determinados tipos. Um _limitante superiror de tipos_ `T <: A` declare que a variável tipo `T` refere-se a um subtipo do tipo `A`. Aqui um exemplo que demonstra um limitante superior de tipo para um parâmetro de tipo da classe `Cage`: -```tut +```scala mdoc abstract class Animal { def name: String } diff --git a/_pt-br/tour/variances.md b/_pt-br/tour/variances.md index 90c248aadf..5abd635810 100644 --- a/_pt-br/tour/variances.md +++ b/_pt-br/tour/variances.md @@ -13,7 +13,7 @@ Scala suporta anotações de variância de parâmetros de tipo de [classes gené Na página sobre [classes genéricas](generic-classes.html) foi dado um exemplo de uma pilha de estado mutável. Explicamos que o tipo definido pela classe `Stack [T]` está sujeito a subtipos invariantes em relação ao parâmetro de tipo. Isso pode restringir a reutilização da abstração de classe. Derivamos agora uma implementação funcional (isto é, imutável) para pilhas que não tem esta restrição. Por favor, note que este é um exemplo avançado que combina o uso de [métodos polimórficos](polymorphic-methods.html), [limites de tipo inferiores](lower-type-bounds.html) e anotações de parâmetros de tipos covariantes em um estilo não trivial. Além disso, fazemos uso de [classes internas](inner-classes.html) para encadear os elementos da pilha sem links explícitos. -```tut +```scala mdoc class Stack[+T] { def push[S >: T](elem: S): Stack[S] = new Stack[S] { override def top: S = elem diff --git a/_ru/cheatsheets/index.md b/_ru/cheatsheets/index.md index 11c1552e74..6ef64ea87a 100644 --- a/_ru/cheatsheets/index.md +++ b/_ru/cheatsheets/index.md @@ -354,4 +354,4 @@ Some(3) match {