Kotlin for Android Developers
Download 1.04 Mb. Pdf ko'rish
|
Kotlin for Android Developers Learn Kotlin the Easy Way While Developing an Android App ( PDFDrive )
- Bu sahifa navigatsiya:
- 28.4 Exceptions
28.3 Sealed classes
Sealed classes are used to represent restricted class hierarchies, which means that the number of classes that extend a sealed class is fixed. It’s similar to an Enum in the sense that you can know beforehand the options you have when looking at the specific type of an object of the parent sealed class. The difference is that enum instances are unique, while sealed classes can have multiple instances which can contain different states. We could implement, for instance, something similar to the Option class in Scala: a type that prevents the use of null by returning a Some class when the object contains a value or the None instance when it’s empty: 28 Extra concepts 142 1 sealed class Option 2 class Some 3 object None : Option 4 } The good thing about sealed classes is that when they are used in a when expression, we can check all the options and won’t need to add the else clause. 1 val result = when (option) { 2 is Option.Some<*> -> "Contains a value" 3 is Option.None -> "Empty" 4 } 28.4 Exceptions In Kotlin, all exceptions implement Throwable , have a message and are unchecked. This means we are not obliged to use try/catch on any of them. That’s not the case in Java, where methods that throw IOException , for instance, need to be surrounded by a try/catch block. Years of dealing with them have shown that checked exceptions were not a good idea. People like Bruce Eckel³¹ , Rod Waldhoff³² or Anders Hejlsberg³³ can give you a better perspective about it. The way to throw an exception is very similar to Java: 1 throw MyException("Exception message") And try expression is identical too: 1 try { 2 // some code 3 } 4 catch (e: SomeException) { 5 // handler 6 } 7 finally { 8 // optional finally block 9 } Both throw and try are expressions in Kotlin, which means they can be assigned to a variable. This is really useful when dealing with edge cases: ³¹ http://www.mindview.net/Etc/Discussions/CheckedExceptions ³² http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html ³³ http://www.artima.com/intv/handcuffs.html 28 Extra concepts 143 1 val s = when(x){ 2 is Int -> "Int instance" 3 is String -> "String instance" 4 else -> throw UnsupportedOperationException("Not valid type") 5 } or 1 val s = try { x as String } catch(e: ClassCastException) { null } |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling