Created
November 7, 2015 12:43
-
-
Save psttf/b35e81e93e46e2825967 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> val i = 123 // значение для сравнения | |
i: Int = 123 | |
scala> def if_i_1(x: Int) = x match { case i => true; case _ => false } // Scala нас предупреждает, что притаком определении сравнение проводиться не будет! | |
<console>:10: warning: patterns after a variable pattern cannot match (SLS 8.1.1) | |
def if_i_1(x: Int) = x match { case i => true; case _ => false } | |
^ | |
<console>:10: warning: unreachable code due to variable pattern 'i' on line 10 | |
def if_i_1(x: Int) = x match { case i => true; case _ => false } | |
^ | |
<console>:10: warning: unreachable code | |
def if_i_1(x: Int) = x match { case i => true; case _ => false } | |
^ | |
if_i_1: (x: Int)Boolean | |
scala> def if_i_2(x: Int) = x match { case ii if ii == i => true; case _ => false } // Здесь все ОК | |
if_i_2: (x: Int)Boolean | |
scala> def if_i_3(x: Int) = x match { case `i` => true; case _ => false } // Этот вариант намного короче, но работает как if_i_3 | |
if_i_3: (x: Int)Boolean | |
scala> if_i_1(321) // С точки зрения сравнения с i, получим неверный результат | |
res0: Boolean = true | |
scala> if_i_2(321) // результат верен | |
res1: Boolean = false | |
scala> if_i_3(321) // результат верен | |
res2: Boolean = false | |
scala> if_i_1(123) // если значение совпадает с ожидаемым, все функции возвращают ожидаемый true | |
res3: Boolean = true | |
scala> if_i_2(123) // если значение совпадает с ожидаемым, все функции возвращают ожидаемый true | |
res4: Boolean = true | |
scala> if_i_3(123) // если значение совпадает с ожидаемым, все функции возвращают ожидаемый true | |
res5: Boolean = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment