diff --git a/_ba/tour/local-type-inference.md b/_ba/tour/local-type-inference.md deleted file mode 100644 index 926c3a4feb..0000000000 --- a/_ba/tour/local-type-inference.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -layout: tour -title: Lokalno zaključivanje tipova (type inference) -language: ba - -discourse: true - -partof: scala-tour - -num: 29 -next-page: operators -previous-page: polymorphic-methods - ---- -Scala ima ugrađen mehanizam zaključivanja tipova koji dozvoljava programeru da izostavi određene anotacije tipova. -Često nije potrebno specificirati tip varijable u Scali, -jer kompajler može sam zaključiti tip iz inicijalizacijskog izraza varijable. -Povratni tipovi metoda također mogu biti izostavljeni jer oni odgovaraju tipu tijela (zadnji izraz u tijelu), koje kompajler sam zaključi. - -Slijedi jedan primjer: - -```tut -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 - def succ(x: Int) = x + 1 // method succ returns Int values -} -``` - -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 -object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) -} -``` - -Također nije obavezno specificirati tipske parametre kada se pozivaju [polimorfne metode](polymorphic-methods.html) -ili kada se [generičke klase](generic-classes.html) instanciraju. -Scala kompajler će zaključiti nedostajuće tipske parametre iz konteksta i iz tipova stvarnih parametara metoda/konstruktora. - -Ovo je primjer koji to ilustrira: - -``` -case class MyPair[A, B](x: A, y: B); -object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // type: MyPair[Int, String] - val q = id(1) // type: Int -} -``` - - -Zadnje dvije linije ovog programa su ekvivalentne sljedećem kodu gdje su svi zaključeni tipovi eksplicitno napisani: - -``` -val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") -val y: Int = id[Int](1) -``` - -U nekim situacijama može biti vrlo opasno osloniti se na Scalin mehanizam zaključivanja tipova: - -```tut:fail -object InferenceTest4 { - var obj = null - obj = new Object() -} -``` - -Ovaj program se ne može kompajlirati jer je zaključeni tip varijable `obj` tip `Null`. -Pošto je jedina vrijednost tog tipa `null`, nemoguće je dodijeliti ovoj varijabli neku drugu vrijednost. diff --git a/_ba/tour/operators.md b/_ba/tour/operators.md index 95d7d977e9..363cf74858 100644 --- a/_ba/tour/operators.md +++ b/_ba/tour/operators.md @@ -9,7 +9,7 @@ partof: scala-tour num: 30 next-page: by-name-parameters -previous-page: local-type-inference +previous-page: type-inference prerequisite-knowledge: case-classes --- diff --git a/_ba/tour/polymorphic-methods.md b/_ba/tour/polymorphic-methods.md index 5765a5c127..250cd850ee 100644 --- a/_ba/tour/polymorphic-methods.md +++ b/_ba/tour/polymorphic-methods.md @@ -9,7 +9,7 @@ partof: scala-tour num: 28 -next-page: local-type-inference +next-page: type-inference previous-page: implicit-conversions prerequisite-knowledge: unified-types diff --git a/_ba/tour/tour-of-scala.md b/_ba/tour/tour-of-scala.md index fd506be132..f1182cb9ad 100644 --- a/_ba/tour/tour-of-scala.md +++ b/_ba/tour/tour-of-scala.md @@ -51,7 +51,7 @@ Konkretno, sistem tipova podržava sljedeće: * implicitne [parametre](implicit-parameters.html) i [konverzije](implicit-conversions.html) * [polimorfne metode](polymorphic-methods.html) -Mehanizam za [lokalno zaključivanje tipova](local-type-inference.html) se brine da korisnik ne mora pisati tipove varijabli +Mehanizam za [lokalno zaključivanje tipova](type-inference.html) se brine da korisnik ne mora pisati tipove varijabli više nego što je potrebno. U kombinaciji, ove mogućnosti su jaka podloga za bezbjedno ponovno iskorištenje programskih apstrakcija i za tipski bezbjedno proširenje softvera. diff --git a/_ba/tour/type-inference.md b/_ba/tour/type-inference.md index 73056dba5d..926c3a4feb 100644 --- a/_ba/tour/type-inference.md +++ b/_ba/tour/type-inference.md @@ -1,15 +1,72 @@ --- layout: tour -title: Type Inference +title: Lokalno zaključivanje tipova (type inference) language: ba discourse: true partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 29 +next-page: operators +previous-page: polymorphic-methods + --- +Scala ima ugrađen mehanizam zaključivanja tipova koji dozvoljava programeru da izostavi određene anotacije tipova. +Često nije potrebno specificirati tip varijable u Scali, +jer kompajler može sam zaključiti tip iz inicijalizacijskog izraza varijable. +Povratni tipovi metoda također mogu biti izostavljeni jer oni odgovaraju tipu tijela (zadnji izraz u tijelu), koje kompajler sam zaključi. + +Slijedi jedan primjer: + +```tut +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 + def succ(x: Int) = x + 1 // method succ returns Int values +} +``` + +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 +object InferenceTest2 { + def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) +} +``` + +Također nije obavezno specificirati tipske parametre kada se pozivaju [polimorfne metode](polymorphic-methods.html) +ili kada se [generičke klase](generic-classes.html) instanciraju. +Scala kompajler će zaključiti nedostajuće tipske parametre iz konteksta i iz tipova stvarnih parametara metoda/konstruktora. + +Ovo je primjer koji to ilustrira: + +``` +case class MyPair[A, B](x: A, y: B); +object InferenceTest3 extends App { + def id[T](x: T) = x + val p = MyPair(1, "scala") // type: MyPair[Int, String] + val q = id(1) // type: Int +} +``` + + +Zadnje dvije linije ovog programa su ekvivalentne sljedećem kodu gdje su svi zaključeni tipovi eksplicitno napisani: + +``` +val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") +val y: Int = id[Int](1) +``` + +U nekim situacijama može biti vrlo opasno osloniti se na Scalin mehanizam zaključivanja tipova: + +```tut:fail +object InferenceTest4 { + var obj = null + obj = new Object() +} +``` -(this section of the tour has not been translated yet. pull request -with translation welcome!) +Ovaj program se ne može kompajlirati jer je zaključeni tip varijable `obj` tip `Null`. +Pošto je jedina vrijednost tog tipa `null`, nemoguće je dodijeliti ovoj varijabli neku drugu vrijednost. diff --git a/_es/tour/local-type-inference.md b/_es/tour/local-type-inference.md deleted file mode 100644 index 0bbf7400fa..0000000000 --- a/_es/tour/local-type-inference.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -layout: tour -title: Inferencia de tipos Local - -discourse: false - -partof: scala-tour - -num: 29 -language: es - -next-page: unified-types -previous-page: self-types ---- - -Scala tiene incorporado un mecanismo de inferencia de tipos el cual permite al programador omitir ciertos tipos de anotaciones. Por ejemplo, generalmente no es necesario especificar el tipo de una variable, ya que el compilador puede deducir el tipo mediante la expresión de inicialización de la variable. También puede generalmente omitirse los tipos de retorno de métodos ya que se corresponden con el tipo del cuerpo, que es inferido por el compilador. - -Aquí hay un ejemplo: - - object InferenceTest1 extends App { - val x = 1 + 2 * 3 // el tipo de x es Int - val y = x.toString() // el tipo de y es String - def succ(x: Int) = x + 1 // el método succ retorna valores Int - } - -Para métodos recursivos, el compilador no es capaz de inferir el tipo resultado. A continuación mostramos un programa el cual falla por esa razón: - - object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) - } - -Tampoco es obligatorio especificar el tipo de los parámetros cuando se trate de [métodos polimórficos](polymorphic-methods.html) o sean instanciadas [clases genéricas](generic-classes.html). El compilador de Scala inferirá esos tipos de parámetros faltantes mediante el contexto y de los tipos de los parámetros reales del método/constructor. - -Aquí se muestra un ejemplo que ilustra esto: - - case class MyPair[A, B](x: A, y: B); - object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // tipo: MyPair[Int, String] - val q = id(1) // tipo: Int - } - -Las últimas dos lineas de este programa son equivalentes al siguiente código, donde todos los tipos inferidos son especificados explicitamente: - - val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") - val y: Int = id[Int](1) - -En algunas situaciones puede ser bastante peligroso confiar en el mecanismo de inferencia de tipos de Scala, como se ilustra en el siguiente ejemplo: - - object InferenceTest4 { - var obj = null - obj = new Object() - } - -Este programa no compila porque el tipo inferido para la variable `obj` es `Null`. Ya que el único valor de ese tipo es `null`, es imposible hacer que esta variable refiera a otro valor. diff --git a/_es/tour/self-types.md b/_es/tour/self-types.md index ff8545c75b..fa430d4887 100644 --- a/_es/tour/self-types.md +++ b/_es/tour/self-types.md @@ -9,7 +9,7 @@ partof: scala-tour num: 27 language: es -next-page: local-type-inference +next-page: type-inference previous-page: lower-type-bounds --- diff --git a/_es/tour/tour-of-scala.md b/_es/tour/tour-of-scala.md index 5c3caa3956..1a060bdf7a 100644 --- a/_es/tour/tour-of-scala.md +++ b/_es/tour/tour-of-scala.md @@ -33,7 +33,7 @@ Scala cuenta con un expresivo sistema de tipado que fuerza estáticamente las ab * [implicit conversions](implicit-conversions.html) * [métodos polimórficos](polymorphic-methods.html) -El [mecanismo de inferencia de tipos locales](local-type-inference.html) se encarga de que el usuario no tengan que anotar el programa con información redundante de tipado. Combinadas, estas características proveen una base poderosa para el reuso seguro de abstracciones de programación y para la extensión segura (en cuanto a tipos) de software. +El [mecanismo de inferencia de tipos locales](type-inference.html) se encarga de que el usuario no tengan que anotar el programa con información redundante de tipado. Combinadas, estas características proveen una base poderosa para el reuso seguro de abstracciones de programación y para la extensión segura (en cuanto a tipos) de software. ## Scala es extensible ## diff --git a/_es/tour/type-inference.md b/_es/tour/type-inference.md index 65a2017fac..0bbf7400fa 100644 --- a/_es/tour/type-inference.md +++ b/_es/tour/type-inference.md @@ -1,15 +1,55 @@ --- layout: tour -title: Type Inference -language: es +title: Inferencia de tipos Local -discourse: true +discourse: false partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 29 +language: es + +next-page: unified-types +previous-page: self-types --- -(this section of the tour has not been translated yet. pull request -with translation welcome!) +Scala tiene incorporado un mecanismo de inferencia de tipos el cual permite al programador omitir ciertos tipos de anotaciones. Por ejemplo, generalmente no es necesario especificar el tipo de una variable, ya que el compilador puede deducir el tipo mediante la expresión de inicialización de la variable. También puede generalmente omitirse los tipos de retorno de métodos ya que se corresponden con el tipo del cuerpo, que es inferido por el compilador. + +Aquí hay un ejemplo: + + object InferenceTest1 extends App { + val x = 1 + 2 * 3 // el tipo de x es Int + val y = x.toString() // el tipo de y es String + def succ(x: Int) = x + 1 // el método succ retorna valores Int + } + +Para métodos recursivos, el compilador no es capaz de inferir el tipo resultado. A continuación mostramos un programa el cual falla por esa razón: + + object InferenceTest2 { + def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) + } + +Tampoco es obligatorio especificar el tipo de los parámetros cuando se trate de [métodos polimórficos](polymorphic-methods.html) o sean instanciadas [clases genéricas](generic-classes.html). El compilador de Scala inferirá esos tipos de parámetros faltantes mediante el contexto y de los tipos de los parámetros reales del método/constructor. + +Aquí se muestra un ejemplo que ilustra esto: + + case class MyPair[A, B](x: A, y: B); + object InferenceTest3 extends App { + def id[T](x: T) = x + val p = MyPair(1, "scala") // tipo: MyPair[Int, String] + val q = id(1) // tipo: Int + } + +Las últimas dos lineas de este programa son equivalentes al siguiente código, donde todos los tipos inferidos son especificados explicitamente: + + val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") + val y: Int = id[Int](1) + +En algunas situaciones puede ser bastante peligroso confiar en el mecanismo de inferencia de tipos de Scala, como se ilustra en el siguiente ejemplo: + + object InferenceTest4 { + var obj = null + obj = new Object() + } + +Este programa no compila porque el tipo inferido para la variable `obj` es `Null`. Ya que el único valor de ese tipo es `null`, es imposible hacer que esta variable refiera a otro valor. diff --git a/_es/tour/unified-types.md b/_es/tour/unified-types.md index 3bdc3541af..d2f8bc76c2 100644 --- a/_es/tour/unified-types.md +++ b/_es/tour/unified-types.md @@ -10,7 +10,7 @@ num: 30 language: es next-page: variances -previous-page: local-type-inference +previous-page: type-inference --- A diferencia de Java, todos los valores en Scala son objetos (incluyendo valores numéricos y funciones). Dado que Scala está basado en clases, todos los valores son instancias de una clase. El diagrama siguiente ilustra esta jerarquía de clases: diff --git a/_ko/tour/local-type-inference.md b/_ko/tour/local-type-inference.md deleted file mode 100644 index 421fb41036..0000000000 --- a/_ko/tour/local-type-inference.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -layout: tour -title: 로컬 타입 추론 - -discourse: false - -partof: scala-tour - -num: 28 -language: ko - -next-page: operators -previous-page: polymorphic-methods ---- - -스칼라는 프로그래머가 특정한 타입 어노테이션을 생략할 수 있도록 해주는 빌트인 타입 추론 기능을 갖추고 있다. 예를 들어, 스칼라에선 컴파일러가 변수의 초기화 표현식으로부터 타입을 추론할 수 있기 때문에 변수의 타입을 지정할 필요가 없을 때가 많다. 또한 메소드의 반환 타입은 본문의 타입과 일치하기 때문에 이 반환 타입 역시 컴파일러가 추론할 수 있고, 주로 생략된다. - -다음 예제를 살펴보자. - - object InferenceTest1 extends App { - val x = 1 + 2 * 3 // x의 타입은 Int다. - val y = x.toString() // y의 타입은 String이다. - def succ(x: Int) = x + 1 // 메소드 succ는 Int 값을 반환한다. - } - -재귀 메소드의 경우는 컴파일러가 결과 타입을 추론할 수 없다. 다음 프로그램에선 이와 같은 이유로 컴파일러가 추론할 수 없다. - - object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) - } - -[다형성 메소드](polymorphic-methods.html)를 호출하거나 [제네릭 클래스](generic-classes.html)를 인스턴스화 할 때 반드시 타입을 지정할 의무는 없다. 스칼라 컴파일러는 컨텍스트와 실제 메소드/생성자 파라미터로부터 생략된 타입 파라미터를 추론한다. - -다음 예제는 이를 나타낸 예제다. - - case class MyPair[A, B](x: A, y: B); - object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // 타입: MyPair[Int, String] - val q = id(1) // 타입: Int - } - -이 프로그램의 마지막 두 줄은 추론된 타입을 명시적으로 나타낸 다음 코드와 동일하다. - - val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") - val y: Int = id[Int](1) - -다음 프로그램에서 나타나는 문제와 같이, 일부 상황에선 스칼라의 타입 추론 기능에 의존하는 것은 상당히 위험할 수 있다. - - object InferenceTest4 { - var obj = null - obj = new Object() - } - -이 프로그램은 변수 `obj`의 타입 추론이 `Null`이기 때문에 컴파일되지 않는다. 해당 타입의 유일한 값이 `null`이기 때문에 이 변수는 다른 값을 나타낼 수 없다. - -윤창석, 이한욱 옮김 \ No newline at end of file diff --git a/_ko/tour/operators.md b/_ko/tour/operators.md index 1eb3c87030..4df29bb1b2 100644 --- a/_ko/tour/operators.md +++ b/_ko/tour/operators.md @@ -10,7 +10,7 @@ num: 29 language: ko next-page: automatic-closures -previous-page: local-type-inference +previous-page: type-inference --- 스칼라에선 단일 파라미터를 취하는 모든 메소드를 *중위 연산자*로 사용할 수 있다. 다음은 `and`와 `or`, `negate` 등의 세 가지 메소드를 정의하고 있는 클래스 `MyBool`의 정의다. @@ -33,4 +33,4 @@ previous-page: local-type-inference def not(x: MyBool) = x.negate; // 여기엔 세미콜론이 필요함 def xor(x: MyBool, y: MyBool) = x.or(y).and(x.and(y).negate) -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/polymorphic-methods.md b/_ko/tour/polymorphic-methods.md index 4d1cbd177e..817c6a5ae0 100644 --- a/_ko/tour/polymorphic-methods.md +++ b/_ko/tour/polymorphic-methods.md @@ -9,7 +9,7 @@ partof: scala-tour num: 27 language: ko -next-page: local-type-inference +next-page: type-inference previous-page: implicit-conversions --- @@ -32,4 +32,4 @@ previous-page: implicit-conversions 트레잇 `App`은 간단한 테스트 프로그램을 작성하도록 설계됐으며, JVM의 코드 최적화 능력에 영향을 주기 때문에 프로덕션 코드에선 사용할 수 없음을 상기하자(스칼라 버전 2.8.x와 그 이전 버전). 그 대신 `def main()`을 사용하도록 하자. -윤창석, 이한욱 옮김 \ No newline at end of file +윤창석, 이한욱 옮김 diff --git a/_ko/tour/tour-of-scala.md b/_ko/tour/tour-of-scala.md index 66dbd5e0e0..091eff518b 100644 --- a/_ko/tour/tour-of-scala.md +++ b/_ko/tour/tour-of-scala.md @@ -34,7 +34,7 @@ next-page: unified-types * 뷰 * [다형 메소드](polymorphic-methods.html) -[로컬 타입 추론 방식](local-type-inference.html)은 사용자가 불필요한 타입 정보를 어노테이션해야 하는 불편함을 줄여준다. 이와 함께, 이런 기능은 프로그래밍 추상화를 안전하게 재사용하고 소프트웨어를 타입 세이프하게 확장하는 강력한 기반이 된다. +[로컬 타입 추론 방식](type-inference.html)은 사용자가 불필요한 타입 정보를 어노테이션해야 하는 불편함을 줄여준다. 이와 함께, 이런 기능은 프로그래밍 추상화를 안전하게 재사용하고 소프트웨어를 타입 세이프하게 확장하는 강력한 기반이 된다. ## 스칼라는 확장성이 높다 ## 실제 개발 상황에선, 도메인 고유 애플리케이션의 개발에 도메인 고유 언어 확장이 필요할 때가 많다. 스칼라는 라이브러리의 형태로 새로운 언어 구성을 쉽고 자연스럽게 추가할 수 있도록 고유한 언어 기능 조합을 제공한다. diff --git a/_ko/tour/type-inference.md b/_ko/tour/type-inference.md index bc56d9b6d0..421fb41036 100644 --- a/_ko/tour/type-inference.md +++ b/_ko/tour/type-inference.md @@ -1,15 +1,57 @@ --- layout: tour -title: Type Inference -language: ko +title: 로컬 타입 추론 -discourse: true +discourse: false partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 28 +language: ko + +next-page: operators +previous-page: polymorphic-methods --- -(this section of the tour has not been translated yet. pull request -with translation welcome!) +스칼라는 프로그래머가 특정한 타입 어노테이션을 생략할 수 있도록 해주는 빌트인 타입 추론 기능을 갖추고 있다. 예를 들어, 스칼라에선 컴파일러가 변수의 초기화 표현식으로부터 타입을 추론할 수 있기 때문에 변수의 타입을 지정할 필요가 없을 때가 많다. 또한 메소드의 반환 타입은 본문의 타입과 일치하기 때문에 이 반환 타입 역시 컴파일러가 추론할 수 있고, 주로 생략된다. + +다음 예제를 살펴보자. + + object InferenceTest1 extends App { + val x = 1 + 2 * 3 // x의 타입은 Int다. + val y = x.toString() // y의 타입은 String이다. + def succ(x: Int) = x + 1 // 메소드 succ는 Int 값을 반환한다. + } + +재귀 메소드의 경우는 컴파일러가 결과 타입을 추론할 수 없다. 다음 프로그램에선 이와 같은 이유로 컴파일러가 추론할 수 없다. + + object InferenceTest2 { + def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) + } + +[다형성 메소드](polymorphic-methods.html)를 호출하거나 [제네릭 클래스](generic-classes.html)를 인스턴스화 할 때 반드시 타입을 지정할 의무는 없다. 스칼라 컴파일러는 컨텍스트와 실제 메소드/생성자 파라미터로부터 생략된 타입 파라미터를 추론한다. + +다음 예제는 이를 나타낸 예제다. + + case class MyPair[A, B](x: A, y: B); + object InferenceTest3 extends App { + def id[T](x: T) = x + val p = MyPair(1, "scala") // 타입: MyPair[Int, String] + val q = id(1) // 타입: Int + } + +이 프로그램의 마지막 두 줄은 추론된 타입을 명시적으로 나타낸 다음 코드와 동일하다. + + val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") + val y: Int = id[Int](1) + +다음 프로그램에서 나타나는 문제와 같이, 일부 상황에선 스칼라의 타입 추론 기능에 의존하는 것은 상당히 위험할 수 있다. + + object InferenceTest4 { + var obj = null + obj = new Object() + } + +이 프로그램은 변수 `obj`의 타입 추론이 `Null`이기 때문에 컴파일되지 않는다. 해당 타입의 유일한 값이 `null`이기 때문에 이 변수는 다른 값을 나타낼 수 없다. + +윤창석, 이한욱 옮김 \ No newline at end of file diff --git a/_pl/tour/local-type-inference.md b/_pl/tour/local-type-inference.md deleted file mode 100644 index c3d057bab9..0000000000 --- a/_pl/tour/local-type-inference.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -layout: tour -title: Lokalna inferencja typów - -discourse: false - -partof: scala-tour - -num: 28 -language: pl -next-page: operators -previous-page: polymorphic-methods ---- - -Scala posiada wbudowany mechanizm inferencji typów, który pozwala programiście pominąć pewne informacje o typach. Przykładowo zazwyczaj nie wymaga się podawania typów zmiennych, gdyż kompilator sam jest w stanie go wydedukować na podstawie typu wyrażenia inicjalizacji zmiennej. Także typy zwracane przez metody mogą być często pominięte, ponieważ odpowiadają one typowi ciała metody, który jest inferowany przez kompilator. - -Oto przykład: - -```tut -object InferenceTest1 extends App { - val x = 1 + 2 * 3 // typem x jest Int - val y = x.toString() // typem y jest String - def succ(x: Int) = x + 1 // metoda succ zwraca wartości typu Int -} -``` - -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 -object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) -} -``` - -Nie jest też konieczne określenie parametrów typu, kiedy są wywoływane [metody polimorficzne](polymorphic-methods.html) lub kiedy tworzymy [klasy generyczne](generic-classes.html). Kompilator Scali sam określi typ brakujących parametrów typów na podstawie kontekstu oraz typów właściwych parametrów metody/konstruktora. - -Oto ilustrujący to przykład: - -``` -case class MyPair[A, B](x: A, y: B); -object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // typ: MyPair[Int, String] - val q = id(1) // typ: Int -} -``` - -Dwie ostatnie linie tego programu są równoważne poniższemu kodu, gdzie wszystkie inferowane typy są określone jawnie: - -``` -val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") -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 -object InferenceTest4 { - var obj = null - obj = new Object() -} -``` - -Ten program się nie skompiluje, ponieważ typ określony dla zmiennej `obj` jest `Null`. Ponieważ jedyną wartością tego typu jest `null`, nie jest możliwe przypisanie tej zmiennej innej wartości. diff --git a/_pl/tour/operators.md b/_pl/tour/operators.md index a6a1c9a057..7cd7747a73 100644 --- a/_pl/tour/operators.md +++ b/_pl/tour/operators.md @@ -9,7 +9,7 @@ partof: scala-tour num: 29 language: pl next-page: automatic-closures -previous-page: local-type-inference +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`: diff --git a/_pl/tour/polymorphic-methods.md b/_pl/tour/polymorphic-methods.md index c40f48dbac..4f8d738202 100644 --- a/_pl/tour/polymorphic-methods.md +++ b/_pl/tour/polymorphic-methods.md @@ -8,7 +8,7 @@ partof: scala-tour num: 27 language: pl -next-page: local-type-inference +next-page: type-inference previous-page: implicit-conversions --- diff --git a/_pl/tour/tour-of-scala.md b/_pl/tour/tour-of-scala.md index 0f3f1d255f..c4b517f7ed 100644 --- a/_pl/tour/tour-of-scala.md +++ b/_pl/tour/tour-of-scala.md @@ -34,7 +34,7 @@ Scala posiada ekspresywny system typów zapewniający, że abstrakcje są używa * [parametry domniemane](implicit-parameters.html) i [konwersje niejawne](implicit-conversions.html) * [metody polimorficzne](polymorphic-methods.html) -[Mechanizm lokalnej inferencji typów](local-type-inference.html) sprawia, że nie jest konieczne podawanie nadmiarowych informacji o typach w programie. W połączeniu te funkcje języka pozwalają na bezpiecznie typowane ponowne wykorzystanie programistycznych abstrakcji. +[Mechanizm lokalnej inferencji typów](type-inference.html) sprawia, że nie jest konieczne podawanie nadmiarowych informacji o typach w programie. W połączeniu te funkcje języka pozwalają na bezpiecznie typowane ponowne wykorzystanie programistycznych abstrakcji. ## Scala jest rozszerzalna ## W praktyce rozwiązania specyficzne dla domeny wymagają odpowiednich rozszerzeń języka. Scala dostarcza unikalne mechanizmy, dzięki którym można łatwo dodawać nowe konstrukcje do języka w postaci bibliotek: diff --git a/_pl/tour/type-inference.md b/_pl/tour/type-inference.md index 0a8ecdeba1..c3d057bab9 100644 --- a/_pl/tour/type-inference.md +++ b/_pl/tour/type-inference.md @@ -1,15 +1,64 @@ --- layout: tour -title: Type Inference -language: pl +title: Lokalna inferencja typów -discourse: true +discourse: false partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 28 +language: pl +next-page: operators +previous-page: polymorphic-methods --- -(this section of the tour has not been translated yet. pull request -with translation welcome!) +Scala posiada wbudowany mechanizm inferencji typów, który pozwala programiście pominąć pewne informacje o typach. Przykładowo zazwyczaj nie wymaga się podawania typów zmiennych, gdyż kompilator sam jest w stanie go wydedukować na podstawie typu wyrażenia inicjalizacji zmiennej. Także typy zwracane przez metody mogą być często pominięte, ponieważ odpowiadają one typowi ciała metody, który jest inferowany przez kompilator. + +Oto przykład: + +```tut +object InferenceTest1 extends App { + val x = 1 + 2 * 3 // typem x jest Int + val y = x.toString() // typem y jest String + def succ(x: Int) = x + 1 // metoda succ zwraca wartości typu Int +} +``` + +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 +object InferenceTest2 { + def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) +} +``` + +Nie jest też konieczne określenie parametrów typu, kiedy są wywoływane [metody polimorficzne](polymorphic-methods.html) lub kiedy tworzymy [klasy generyczne](generic-classes.html). Kompilator Scali sam określi typ brakujących parametrów typów na podstawie kontekstu oraz typów właściwych parametrów metody/konstruktora. + +Oto ilustrujący to przykład: + +``` +case class MyPair[A, B](x: A, y: B); +object InferenceTest3 extends App { + def id[T](x: T) = x + val p = MyPair(1, "scala") // typ: MyPair[Int, String] + val q = id(1) // typ: Int +} +``` + +Dwie ostatnie linie tego programu są równoważne poniższemu kodu, gdzie wszystkie inferowane typy są określone jawnie: + +``` +val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") +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 +object InferenceTest4 { + var obj = null + obj = new Object() +} +``` + +Ten program się nie skompiluje, ponieważ typ określony dla zmiennej `obj` jest `Null`. Ponieważ jedyną wartością tego typu jest `null`, nie jest możliwe przypisanie tej zmiennej innej wartości. diff --git a/_pt-br/tour/local-type-inference.md b/_pt-br/tour/local-type-inference.md deleted file mode 100644 index a9f5de8f54..0000000000 --- a/_pt-br/tour/local-type-inference.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -layout: tour -title: Inferência de Tipo Local - -discourse: false - -partof: scala-tour - -num: 28 -next-page: operators -previous-page: polymorphic-methods -language: pt-br ---- - -Scala tem um mecanismo nativo de inferência de tipos que permite ao programador omitir certas anotações. Por exemplo, muitas vezes não é necessário especificar o tipo de uma variável, uma vez que o compilador pode deduzir o tipo a partir da expressão de inicialização da variável. Os tipos de retorno de métodos também podem muitas vezes ser omitidos, uma vez que correspondem ao tipo do corpo do método, que é inferido pelo compilador. - -Por exemplo: - -```tut -object InferenceTest1 extends App { - val x = 1 + 2 * 3 // o tipo de x é Int - val y = x.toString() // o tipo de y é String - def succ(x: Int) = x + 1 // o método succ retorna um valor Int -} -``` - -Para métodos recursivos, o compilador não é capaz de inferir o tipo de retorno. - -Exemplo de um método que não irá compilar por este motivo: - -```tut:fail -object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) -} -``` - -Também não é obrigatório especificar os tipos dos parâmetros quando [métodos polimórficos](polymorphic-methods.html) são invocados ou são criadas instâncias de [classes genéricas](generic-classes.html). O compilador Scala irá inferir tais parâmetros que não estão presentes a partir do contexto das chamadas e dos tipos dos parâmetros reais do método/construtor. - -Por exemplo: - -``` -case class MyPair[A, B](x: A, y: B); -object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // type: MyPair[Int, String] - val q = id(1) // type: Int -} -``` - -As duas últimas linhas deste programa são equivalentes ao seguinte código onde todos os tipos inferidos são declarados explicitamente: - -``` -val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") -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 -object InferenceTest4 { - var obj = null - obj = new Object() -} -``` - -Este programa não compila porque o tipo inferido para a variável `obj` é `Null`. Como o único valor desse tipo é `null`, é impossível fazer essa variável se referir a outro valor. diff --git a/_pt-br/tour/operators.md b/_pt-br/tour/operators.md index 8e97ec3912..b9d53f1ae8 100644 --- a/_pt-br/tour/operators.md +++ b/_pt-br/tour/operators.md @@ -8,7 +8,7 @@ partof: scala-tour num: 29 next-page: automatic-closures -previous-page: local-type-inference +previous-page: type-inference language: pt-br --- diff --git a/_pt-br/tour/polymorphic-methods.md b/_pt-br/tour/polymorphic-methods.md index 6d6c9150b7..359781e966 100644 --- a/_pt-br/tour/polymorphic-methods.md +++ b/_pt-br/tour/polymorphic-methods.md @@ -8,7 +8,7 @@ partof: scala-tour num: 27 -next-page: local-type-inference +next-page: type-inference previous-page: implicit-conversions language: pt-br --- diff --git a/_pt-br/tour/tour-of-scala.md b/_pt-br/tour/tour-of-scala.md index 01f75ac1a9..2f19f11133 100644 --- a/_pt-br/tour/tour-of-scala.md +++ b/_pt-br/tour/tour-of-scala.md @@ -34,7 +34,7 @@ Scala é equipada com um expressivo sistema de tipos que reforça estaticamente * [parâmetros implícitos](implicit-parameters.html) e [conversões implícitas](implicit-conversions.html) * [métodos polimórficos](polymorphic-methods.html) -Um [mecanismo de inferência de tipo local](local-type-inference.html) se encarrega para que o usuário não seja obrigado a anotar o programa com informações reduntante de tipos. Combinados, esses recursos fornecem uma base poderosa para a reutilização segura de abstrações de programação e para a extensão de tipos seguro do software. +Um [mecanismo de inferência de tipo local](type-inference.html) se encarrega para que o usuário não seja obrigado a anotar o programa com informações reduntante de tipos. Combinados, esses recursos fornecem uma base poderosa para a reutilização segura de abstrações de programação e para a extensão de tipos seguro do software. ## Scala é extensível ## diff --git a/_pt-br/tour/type-inference.md b/_pt-br/tour/type-inference.md index 2426517038..a9f5de8f54 100644 --- a/_pt-br/tour/type-inference.md +++ b/_pt-br/tour/type-inference.md @@ -1,15 +1,67 @@ --- layout: tour -title: Type Inference -language: pt-br +title: Inferência de Tipo Local -discourse: true +discourse: false partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 28 +next-page: operators +previous-page: polymorphic-methods +language: pt-br --- -(this section of the tour has not been translated yet. pull request -with translation welcome!) +Scala tem um mecanismo nativo de inferência de tipos que permite ao programador omitir certas anotações. Por exemplo, muitas vezes não é necessário especificar o tipo de uma variável, uma vez que o compilador pode deduzir o tipo a partir da expressão de inicialização da variável. Os tipos de retorno de métodos também podem muitas vezes ser omitidos, uma vez que correspondem ao tipo do corpo do método, que é inferido pelo compilador. + +Por exemplo: + +```tut +object InferenceTest1 extends App { + val x = 1 + 2 * 3 // o tipo de x é Int + val y = x.toString() // o tipo de y é String + def succ(x: Int) = x + 1 // o método succ retorna um valor Int +} +``` + +Para métodos recursivos, o compilador não é capaz de inferir o tipo de retorno. + +Exemplo de um método que não irá compilar por este motivo: + +```tut:fail +object InferenceTest2 { + def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) +} +``` + +Também não é obrigatório especificar os tipos dos parâmetros quando [métodos polimórficos](polymorphic-methods.html) são invocados ou são criadas instâncias de [classes genéricas](generic-classes.html). O compilador Scala irá inferir tais parâmetros que não estão presentes a partir do contexto das chamadas e dos tipos dos parâmetros reais do método/construtor. + +Por exemplo: + +``` +case class MyPair[A, B](x: A, y: B); +object InferenceTest3 extends App { + def id[T](x: T) = x + val p = MyPair(1, "scala") // type: MyPair[Int, String] + val q = id(1) // type: Int +} +``` + +As duas últimas linhas deste programa são equivalentes ao seguinte código onde todos os tipos inferidos são declarados explicitamente: + +``` +val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") +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 +object InferenceTest4 { + var obj = null + obj = new Object() +} +``` + +Este programa não compila porque o tipo inferido para a variável `obj` é `Null`. Como o único valor desse tipo é `null`, é impossível fazer essa variável se referir a outro valor. diff --git a/_tour/local-type-inference.md b/_tour/local-type-inference.md deleted file mode 100644 index e1625bcc68..0000000000 --- a/_tour/local-type-inference.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -layout: tour -title: Local Type Inference - -discourse: true - -partof: scala-tour - -num: 29 -next-page: operators -previous-page: polymorphic-methods - -redirect_from: "/tutorials/tour/local-type-inference.html" ---- -Scala has a built-in type inference mechanism which allows the programmer to omit certain type annotations. It is, for instance, often not necessary in Scala to specify the type of a variable, since the compiler can deduce the type from the initialization expression of the variable. Also return types of methods can often be omitted since they correspond to the type of the body, which gets inferred by the compiler. - -Here is an example: - -```tut -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 - def succ(x: Int) = x + 1 // method succ returns Int values -} -``` - -For recursive methods, the compiler is not able to infer a result type. Here is a program which will fail the compiler for this reason: - -```tut:fail -object InferenceTest2 { - def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1) -} -``` - -It is also not compulsory to specify type parameters when [polymorphic methods](polymorphic-methods.html) are called or [generic classes](generic-classes.html) are instantiated. The Scala compiler will infer such missing type parameters from the context and from the types of the actual method/constructor parameters. - -Here is an example which illustrates this: - -``` -case class MyPair[A, B](x: A, y: B); -object InferenceTest3 extends App { - def id[T](x: T) = x - val p = MyPair(1, "scala") // type: MyPair[Int, String] - val q = id(1) // type: Int -} -``` - -The last two lines of this program are equivalent to the following code where all inferred types are made explicit: - -``` -val x: MyPair[Int, String] = MyPair[Int, String](1, "scala") -val y: Int = id[Int](1) -``` - -In some situations it can be quite dangerous to rely on Scala's type inference mechanism as the following program shows: - -```tut:fail -object InferenceTest4 { - var obj = null - obj = new Object() -} -``` - -This program does not compile because the type inferred for variable `obj` is `Null`. Since the only value of that type is `null`, it is impossible to make this variable refer to another value. diff --git a/_tour/operators.md b/_tour/operators.md index 932fccba97..51e92d9b67 100644 --- a/_tour/operators.md +++ b/_tour/operators.md @@ -8,7 +8,7 @@ partof: scala-tour num: 30 next-page: by-name-parameters -previous-page: local-type-inference +previous-page: type-inference prerequisite-knowledge: case-classes redirect_from: "/tutorials/tour/operators.html" diff --git a/_tour/polymorphic-methods.md b/_tour/polymorphic-methods.md index e7c68370e8..8f9cb4525f 100644 --- a/_tour/polymorphic-methods.md +++ b/_tour/polymorphic-methods.md @@ -8,7 +8,7 @@ partof: scala-tour num: 28 -next-page: local-type-inference +next-page: type-inference previous-page: implicit-conversions prerequisite-knowledge: unified-types diff --git a/_tour/tour-of-scala.md b/_tour/tour-of-scala.md index 1cefe23c23..8520d2ce98 100644 --- a/_tour/tour-of-scala.md +++ b/_tour/tour-of-scala.md @@ -35,7 +35,7 @@ Scala is equipped with an expressive type system that enforces statically that a * [implicit parameters](implicit-parameters.html) and [conversions](implicit-conversions.html) * [polymorphic methods](polymorphic-methods.html) -A [local type inference mechanism](local-type-inference.html) takes care that the user is not required to annotate the program with redundant type information. In combination, these features provide a powerful basis for the safe reuse of programming abstractions and for the type-safe extension of software. +[Type inference](type-inference.html) means the user is not required to annotate code with redundant type information. In combination, these features provide a powerful basis for the safe reuse of programming abstractions and for the type-safe extension of software. ## Scala is extensible ## diff --git a/_tour/type-inference.md b/_tour/type-inference.md index 782dfd62c7..c024aeae26 100644 --- a/_tour/type-inference.md +++ b/_tour/type-inference.md @@ -6,8 +6,9 @@ discourse: true partof: scala-tour -num: 36 -previous-page: packages-and-imports +num: 29 +next-page: operators +previous-page: polymorphic-methods --- The Scala compiler can often infer the type of an expression so you don't have to declare it explicitly.