├── .gitattributes ├── .gitignore ├── Chapter01 ├── gradle_project │ ├── build.gradle │ ├── gradle.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── programming │ │ │ └── kotlin │ │ │ └── chapter01 │ │ │ └── CarManufacturer.java │ │ └── kotlin │ │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter01 │ │ ├── Program.kt │ │ ├── Student.java │ │ └── Task.kt └── maven-mix │ ├── pom.xml │ └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── programming │ │ │ └── kotlin │ │ │ └── CarManufacturer.java │ └── kotlin │ │ └── com │ │ └── programming │ │ └── kotlin │ │ ├── Hello.kt │ │ ├── Student.java │ │ └── Task.kt │ └── test │ └── kotlin │ └── com │ └── programming │ └── kotlin │ └── HelloTest.kt ├── Chapter02 └── src │ └── main │ ├── java │ ├── KotlinFromJava.java │ └── com │ │ └── packt │ │ └── chapter4 │ │ ├── OverloadsForDefaults.java │ │ └── ThrowsFromJava.java │ └── kotlin │ └── com │ └── packt │ ├── chapter2 │ ├── JavaCast.java │ ├── JavaIf.java │ ├── array.kt │ ├── basic_syntax.kt │ ├── bitwise.kt │ ├── boolean.kt │ ├── char.kt │ ├── col1.kt │ ├── comments.kt │ ├── controlflowasexpression.kt │ ├── equals.kt │ ├── exceptions.kt │ ├── explicitWidening.kt │ ├── forloop.kt │ ├── literals.kt │ ├── new.kt │ ├── null.kt │ ├── package.kt │ ├── private.kt │ ├── range1.kt │ ├── return.kt │ ├── smartcasts.kt │ ├── string.kt │ ├── stringconcat.kt │ ├── stringtemplate.kt │ ├── this.kt │ ├── when.kt │ └── while.kt │ ├── chapter4 │ ├── 4.1.kt │ ├── 4.10.kt │ ├── 4.11.operators.kt │ ├── 4.12.kt │ ├── 4.13.kt │ ├── 4.14.vararg.kt │ ├── 4.15.stdlib.kt │ ├── 4.16.genericfuncs.kt │ ├── 4.17.kt │ ├── 4.2.kt │ ├── 4.20.kt │ ├── 4.22.kotlin_from_java.kt │ ├── 4.3.kt │ ├── 4.4.kt │ ├── 4.5.kt │ ├── 4.6.kt │ ├── 4.7.defaults.kt │ ├── 4.8.kt │ ├── 4.9.kt │ ├── Matrix.java │ ├── Named.java │ ├── infix.kt │ ├── matrix.kt │ └── singlexpfun.kt │ ├── chapter5 │ ├── 5.1.HigherOrder.kt │ ├── 5.10.Memoization.kt │ ├── 5.11.Typealias.kt │ ├── 5.12.Either.kt │ ├── 5.13.CustomDsl.kt │ ├── 5.14.ErrorAccumulation.kt │ ├── 5.2.Closures.kt │ ├── 5.3.Anonymous.kt │ ├── 5.4.References.kt │ ├── 5.5.Receivers.kt │ ├── 5.7.Composition.kt │ ├── 5.8.Inline.kt │ └── 5.9.Currying.kt │ ├── myproject │ ├── constants │ │ └── import1.kt │ └── import2.kt │ └── otherproject │ └── Foo.kt ├── Chapter03 ├── inheritance │ ├── .idea │ │ └── vcs.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ │ └── main │ │ └── kotlin │ │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter03 │ │ ├── A.kt │ │ ├── Abstract.kt │ │ ├── Airplane.kt │ │ ├── AmphibiousCar.kt │ │ ├── Base.kt │ │ ├── CardPayment.kt │ │ ├── CardType.kt │ │ ├── ChequePayment.kt │ │ ├── Container.kt │ │ ├── Document.kt │ │ ├── Image.kt │ │ ├── IntBinaryTreee.kt │ │ ├── Payment.kt │ │ ├── Program.kt │ │ ├── Singleton.kt │ │ ├── Static.kt │ │ └── Student.kt └── polymorphism │ ├── build.gradle │ ├── gradle.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle │ └── src │ └── main │ └── kotlin │ └── com │ └── programming │ └── kotlin │ └── chapter03 │ ├── Ellipsis.kt │ ├── Program.kt │ ├── Rectangular.kt │ └── Shape.kt ├── Chapter04 └── src │ └── main │ ├── java │ ├── KotlinFromJava.java │ └── com │ │ └── packt │ │ └── chapter4 │ │ ├── OverloadsForDefaults.java │ │ └── ThrowsFromJava.java │ └── kotlin │ └── com │ └── packt │ ├── chapter2 │ ├── JavaCast.java │ ├── JavaIf.java │ ├── array.kt │ ├── basic_syntax.kt │ ├── bitwise.kt │ ├── boolean.kt │ ├── char.kt │ ├── col1.kt │ ├── comments.kt │ ├── controlflowasexpression.kt │ ├── equals.kt │ ├── exceptions.kt │ ├── explicitWidening.kt │ ├── forloop.kt │ ├── literals.kt │ ├── new.kt │ ├── null.kt │ ├── package.kt │ ├── private.kt │ ├── range1.kt │ ├── return.kt │ ├── smartcasts.kt │ ├── string.kt │ ├── stringconcat.kt │ ├── stringtemplate.kt │ ├── this.kt │ ├── when.kt │ └── while.kt │ ├── chapter4 │ ├── 4.1.kt │ ├── 4.10.kt │ ├── 4.11.operators.kt │ ├── 4.12.kt │ ├── 4.13.kt │ ├── 4.14.vararg.kt │ ├── 4.15.stdlib.kt │ ├── 4.16.genericfuncs.kt │ ├── 4.17.kt │ ├── 4.2.kt │ ├── 4.20.kt │ ├── 4.22.kotlin_from_java.kt │ ├── 4.3.kt │ ├── 4.4.kt │ ├── 4.5.kt │ ├── 4.6.kt │ ├── 4.7.defaults.kt │ ├── 4.8.kt │ ├── 4.9.kt │ ├── Matrix.java │ ├── Named.java │ ├── infix.kt │ ├── matrix.kt │ └── singlexpfun.kt │ ├── chapter5 │ ├── 5.1.HigherOrder.kt │ ├── 5.10.Memoization.kt │ ├── 5.11.Typealias.kt │ ├── 5.12.Either.kt │ ├── 5.13.CustomDsl.kt │ ├── 5.14.ErrorAccumulation.kt │ ├── 5.2.Closures.kt │ ├── 5.3.Anonymous.kt │ ├── 5.4.References.kt │ ├── 5.5.Receivers.kt │ ├── 5.7.Composition.kt │ ├── 5.8.Inline.kt │ └── 5.9.Currying.kt │ ├── myproject │ ├── constants │ │ └── import1.kt │ └── import2.kt │ └── otherproject │ └── Foo.kt ├── Chapter05 └── src │ └── main │ ├── java │ ├── KotlinFromJava.java │ └── com │ │ └── packt │ │ └── chapter4 │ │ ├── OverloadsForDefaults.java │ │ └── ThrowsFromJava.java │ └── kotlin │ └── com │ └── packt │ ├── chapter2 │ ├── JavaCast.java │ ├── JavaIf.java │ ├── array.kt │ ├── basic_syntax.kt │ ├── bitwise.kt │ ├── boolean.kt │ ├── char.kt │ ├── col1.kt │ ├── comments.kt │ ├── controlflowasexpression.kt │ ├── equals.kt │ ├── exceptions.kt │ ├── explicitWidening.kt │ ├── forloop.kt │ ├── literals.kt │ ├── new.kt │ ├── null.kt │ ├── package.kt │ ├── private.kt │ ├── range1.kt │ ├── return.kt │ ├── smartcasts.kt │ ├── string.kt │ ├── stringconcat.kt │ ├── stringtemplate.kt │ ├── this.kt │ ├── when.kt │ └── while.kt │ ├── chapter4 │ ├── 4.1.kt │ ├── 4.10.kt │ ├── 4.11.operators.kt │ ├── 4.12.kt │ ├── 4.13.kt │ ├── 4.14.vararg.kt │ ├── 4.15.stdlib.kt │ ├── 4.16.genericfuncs.kt │ ├── 4.17.kt │ ├── 4.2.kt │ ├── 4.20.kt │ ├── 4.22.kotlin_from_java.kt │ ├── 4.3.kt │ ├── 4.4.kt │ ├── 4.5.kt │ ├── 4.6.kt │ ├── 4.7.defaults.kt │ ├── 4.8.kt │ ├── 4.9.kt │ ├── Matrix.java │ ├── Named.java │ ├── infix.kt │ ├── matrix.kt │ └── singlexpfun.kt │ ├── chapter5 │ ├── 5.1.HigherOrder.kt │ ├── 5.10.Memoization.kt │ ├── 5.11.Typealias.kt │ ├── 5.12.Either.kt │ ├── 5.13.CustomDsl.kt │ ├── 5.14.ErrorAccumulation.kt │ ├── 5.2.Closures.kt │ ├── 5.3.Anonymous.kt │ ├── 5.4.References.kt │ ├── 5.5.Receivers.kt │ ├── 5.7.Composition.kt │ ├── 5.8.Inline.kt │ └── 5.9.Currying.kt │ ├── myproject │ ├── constants │ │ └── import1.kt │ └── import2.kt │ └── otherproject │ └── Foo.kt ├── Chapter06 ├── build.gradle ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── kotlin │ └── com │ └── programming │ └── kotlin │ └── chapter06 │ ├── DelayedInit.kt │ ├── Delegate.kt │ ├── LazyProperty.kt │ ├── Lookup.kt │ ├── Measure.kt │ ├── NonNullProp.kt │ ├── Player.kt │ ├── Program.kt │ ├── PropsByMap.kt │ ├── Shape.kt │ ├── Student.kt │ ├── Trivial.kt │ ├── WithInheritance.kt │ ├── WithObservableProp.kt │ └── WithPrivateSetter.kt ├── Chapter07 └── src │ └── main │ ├── java │ ├── KotlinFromJava.java │ └── com │ │ └── packt │ │ ├── chapter4 │ │ ├── OverloadsForDefaults.java │ │ └── ThrowsFromJava.java │ │ └── chapter7 │ │ ├── StaticFuncs.java │ │ └── ThrowsExample.java │ └── kotlin │ └── com │ └── packt │ ├── chapter2 │ ├── JavaCast.java │ ├── JavaIf.java │ ├── array.kt │ ├── basic_syntax.kt │ ├── bitwise.kt │ ├── boolean.kt │ ├── char.kt │ ├── col1.kt │ ├── comments.kt │ ├── controlflowasexpression.kt │ ├── equals.kt │ ├── exceptions.kt │ ├── explicitWidening.kt │ ├── forloop.kt │ ├── literals.kt │ ├── new.kt │ ├── null.kt │ ├── package.kt │ ├── private.kt │ ├── range1.kt │ ├── return.kt │ ├── smartcasts.kt │ ├── string.kt │ ├── stringconcat.kt │ ├── stringtemplate.kt │ ├── this.kt │ ├── when.kt │ └── while.kt │ ├── chapter4 │ ├── 4.1.kt │ ├── 4.10.kt │ ├── 4.11.operators.kt │ ├── 4.12.kt │ ├── 4.13.kt │ ├── 4.14.vararg.kt │ ├── 4.15.stdlib.kt │ ├── 4.16.genericfuncs.kt │ ├── 4.17.kt │ ├── 4.2.kt │ ├── 4.20.kt │ ├── 4.22.kotlin_from_java.kt │ ├── 4.3.kt │ ├── 4.4.kt │ ├── 4.5.kt │ ├── 4.6.kt │ ├── 4.7.defaults.kt │ ├── 4.8.kt │ ├── 4.9.kt │ ├── Matrix.java │ ├── Named.java │ ├── infix.kt │ ├── matrix.kt │ └── singlexpfun.kt │ ├── chapter5 │ ├── 5.1.HigherOrder.kt │ ├── 5.10.Memoization.kt │ ├── 5.11.Typealias.kt │ ├── 5.12.Either.kt │ ├── 5.13.CustomDsl.kt │ ├── 5.14.ErrorAccumulation.kt │ ├── 5.2.Closures.kt │ ├── 5.3.Anonymous.kt │ ├── 5.4.References.kt │ ├── 5.5.Receivers.kt │ ├── 5.7.Composition.kt │ ├── 5.8.Inline.kt │ └── 5.9.Currying.kt │ ├── chapter7 │ ├── 7.10.Instantiation.kt │ ├── 7.11.Constructors.kt │ ├── 7.12.Objects.kt │ ├── 7.13.UsefulKClassProperties.kt │ ├── 7.14.functions.kt │ ├── 7.15.annotations.kt │ ├── 7.16.1.jvmnameannotation.kt │ ├── 7.16.2.JvmStatic.kt │ ├── 7.16.3.Throws.kt │ ├── 7.16.4.JvmOverloads.kt │ ├── 7.4.SafeNullAccess.kt │ ├── 7.5.ElvisOperator.kt │ ├── 7.6.Safecasts.kt │ ├── 7.7.optionals.kt │ └── 7.9.KClass.kt │ ├── myproject │ ├── constants │ │ └── import1.kt │ └── import2.kt │ └── otherproject │ └── Foo.kt ├── Chapter08 └── chapter8 │ └── src │ └── main │ └── kotlin │ └── com │ └── packt │ └── chapter8 │ ├── 8.1.ParameterizedFunctions.kt │ ├── 8.10.AlgebraicDataType.kt │ ├── 8.2.ParameterizedTypes.kt │ ├── 8.3.TypeBounds.kt │ ├── 8.4.Variance.kt │ ├── 8.5.Nothing.kt │ ├── 8.6.TypeProjection.kt │ ├── 8.7.Erasure.kt │ ├── 8.8.Reification.kt │ └── 8.9.fbounded.kt ├── Chapter09 ├── build.gradle ├── gradle.properties ├── settings.gradle └── src │ └── main │ ├── java │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter09 │ │ ├── BlogEntryJ.java │ │ ├── Sensor.java │ │ └── SomeProgram.java │ └── kotlin │ └── com │ └── programming │ └── kotlin │ └── chapter09 │ ├── BlogEntry.kt │ ├── Either.kt │ ├── Email.kt │ ├── Program.kt │ ├── SensorExtension.kt │ └── Vector3.kt ├── Chapter10 ├── build.gradle ├── gradle.properties ├── settings.gradle └── src │ └── main │ ├── java │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter10 │ │ └── CollectionsJ.java │ ├── kotlin │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter10 │ │ ├── ArraysCollection.kt │ │ ├── IndexedAccess.kt │ │ ├── ListsCollection.kt │ │ ├── MapsCollection.kt │ │ ├── Program.kt │ │ ├── ReadOnly.kt │ │ ├── SequencesCollection.kt │ │ └── SetsCollection.kt │ └── resources │ └── afile.txt ├── Chapter11 └── chapter11 │ └── src │ └── main │ └── kotlin │ └── com │ └── packt │ └── chapter11 │ ├── 11.10.Config.kt │ ├── 11.11.Resources.kt │ ├── 11.2.Specs.kt │ ├── 11.3.Matchers.kt │ ├── 11.4.CustomMatchers.kt │ ├── 11.5.Inspectors.kt │ ├── 11.6.Interceptors.kt │ ├── 11.6.ProjectConfig.kt │ ├── 11.7.PropertyTesting.kt │ ├── 11.8.TableDrivenTesting.kt │ └── 11.9.Eventually.kt ├── Chapter12 ├── cassandra-config │ ├── pom.xml │ └── src │ │ ├── assembly │ │ └── conductr-bundle.xml │ │ └── bundle │ │ ├── bundle.conf │ │ ├── cassandra-config │ │ ├── cassandra.yaml │ │ ├── jvm.options │ │ └── logback.xml │ │ └── runtime-config.sh ├── hello-api │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── programming │ │ │ └── kotlin │ │ │ └── chapter12 │ │ │ └── hello │ │ │ └── api │ │ │ ├── GreetingMessage.java │ │ │ └── HelloService.java │ │ └── kotlin │ │ └── com.programming.kotlin.chapter12.hello.api │ │ ├── GreetingMessage.kt │ │ ├── GreetingsMessageSerializer.kt │ │ ├── HelloService.kt │ │ └── Jackson.kt ├── hello-impl │ ├── pom.xml │ └── src │ │ ├── assembly │ │ └── conductr-bundle.xml │ │ ├── bundle │ │ └── bundle.conf │ │ ├── main │ │ ├── java │ │ │ └── com │ │ │ │ └── programming │ │ │ │ └── kotlin │ │ │ │ └── chapter12 │ │ │ │ └── hello │ │ │ │ └── impl │ │ │ │ ├── HelloCommand.java │ │ │ │ ├── HelloEntity.java │ │ │ │ ├── HelloEvent.java │ │ │ │ ├── HelloModule.java │ │ │ │ ├── HelloServiceImpl.java │ │ │ │ └── HelloState.java │ │ ├── kotlin │ │ │ └── com.programming.kotlin.chapter12.hello.impl │ │ │ │ ├── HelloCommand.kt │ │ │ │ ├── HelloEntity.kt │ │ │ │ ├── HelloEvent.kt │ │ │ │ ├── HelloModule.kt │ │ │ │ ├── HelloServiceImpl.kt │ │ │ │ └── HelloState.kt │ │ └── resources │ │ │ └── application.conf │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── programming │ │ │ └── kotlin │ │ │ └── chapter12 │ │ │ └── hello │ │ │ └── impl │ │ │ ├── HelloEntityTest.java │ │ │ └── HelloServiceTest.java │ │ └── resources │ │ └── logback-test.xml ├── integration-tests │ ├── pom.xml │ └── src │ │ └── test │ │ ├── java │ │ └── com │ │ │ └── programming │ │ │ └── kotlin │ │ │ └── chapter12 │ │ │ └── it │ │ │ └── StreamIT.java │ │ └── resources │ │ ├── application.conf │ │ └── logback-test.xml ├── pom.xml ├── stream-api │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter12 │ │ └── stream │ │ └── api │ │ └── StreamService.java └── stream-impl │ ├── pom.xml │ └── src │ ├── assembly │ └── conductr-bundle.xml │ ├── bundle │ └── bundle.conf │ └── main │ ├── java │ └── com │ │ └── programming │ │ └── kotlin │ │ └── chapter12 │ │ └── stream │ │ └── impl │ │ ├── StreamModule.java │ │ └── StreamServiceImpl.java │ └── resources │ └── application.conf ├── Chapter13 └── src │ └── main │ └── kotlin │ └── com │ └── packt │ └── chapter13 │ ├── 13.10.CyclicBarrier.kt │ ├── 13.11.Asynchronous.kt │ ├── 13.12.Futures.kt │ ├── 13.2.Thread.kt │ ├── 13.4.Executors.kt │ ├── 13.5.RaceConditions.kt │ ├── 13.6.Semaphore.kt │ ├── 13.7.ConcurrentCollections.kt │ ├── 13.8.Atomics.kt │ └── 13.9.CountdownLatch.kt ├── Chapter14 ├── async.kt ├── cancel_children.kt ├── child_failure.kt ├── concurrent_ecommerce.kt ├── concurrent_ecommerce_async.kt ├── debugging.kt ├── debugging_named.kt ├── dispatcher_default.kt ├── dispatcher_io.kt ├── dispatcher_wrapper.kt ├── exception_handler.kt ├── exception_handler_await.kt ├── first_coroutine.kt ├── intro.kt ├── jobs.kt ├── join.kt ├── lazy.kt ├── nested_coroutines.kt ├── parent_cancellation.kt ├── parent_failure.kt ├── runBlocking.kt ├── second_coroutine.kt ├── sequential.kt ├── sequential_awaits.kt ├── sequential_ecommerce.kt ├── sequential_with_input.kt ├── supervisor_scope.kt ├── will_block_before_exit.kt ├── will_exit.kt └── withContext.kt ├── Chapter15 ├── blocking_calls.kt ├── callbacks.kt ├── channel_capacity.kt ├── channel_conflated.kt ├── channel_iteration.kt ├── channel_producer.kt ├── channel_ticker.kt ├── channels_rendezvous.kt ├── select_channel.kt ├── select_closed.kt └── select_deferred.kt ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /Chapter01/gradle_project/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter01/gradle_project/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'chapter01' 2 | 3 | -------------------------------------------------------------------------------- /Chapter01/gradle_project/src/main/java/com/programming/kotlin/chapter01/CarManufacturer.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter01; 2 | 3 | public class CarManufacturer { 4 | private final String name; 5 | 6 | public CarManufacturer(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter01/gradle_project/src/main/kotlin/com/programming/kotlin/chapter01/Program.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter01 2 | 3 | fun main(args: Array) { 4 | println("Hellow World!") 5 | 6 | val student= Student("Alexandra Miller") 7 | println("Student name:${student.name}") 8 | 9 | val carManufacturer=CarManufacturer("Mercedes") 10 | println("Car manufacturer:${carManufacturer.name}") 11 | } 12 | -------------------------------------------------------------------------------- /Chapter01/gradle_project/src/main/kotlin/com/programming/kotlin/chapter01/Student.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter01; 2 | 3 | public class Student { 4 | private final String name; 5 | 6 | public Student(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter01/gradle_project/src/main/kotlin/com/programming/kotlin/chapter01/Task.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter01 2 | 3 | class Task(val id:Int, val title:String) -------------------------------------------------------------------------------- /Chapter01/maven-mix/src/main/java/com/programming/kotlin/CarManufacturer.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin; 2 | 3 | public class CarManufacturer { 4 | private final String name; 5 | 6 | public CarManufacturer(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter01/maven-mix/src/main/kotlin/com/programming/kotlin/Hello.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin 2 | 3 | fun main(args: Array) { 4 | val task = Task(1, "Mix Java and Kotlin code", "Jack Smith") 5 | println("Task:${task.title}") 6 | 7 | val student = Student("Jenny Wood") 8 | println("Student:${student.name}") 9 | 10 | val carManufacturer = CarManufacturer("Honda") 11 | println("Car manufacture:${carManufacturer.name}") 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Chapter01/maven-mix/src/main/kotlin/com/programming/kotlin/Student.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin; 2 | 3 | 4 | public class Student { 5 | private final String name; 6 | 7 | public Student(String name) { 8 | this.name = name; 9 | } 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter01/maven-mix/src/main/kotlin/com/programming/kotlin/Task.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin 2 | 3 | 4 | class Task(val id: Int, val title: String, val assigenedToName: String) -------------------------------------------------------------------------------- /Chapter01/maven-mix/src/test/kotlin/com/programming/kotlin/HelloTest.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin 2 | 3 | import org.junit.Test 4 | import kotlin.test.assertEquals 5 | 6 | class HelloTest { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /Chapter02/src/main/java/KotlinFromJava.java: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Chapter4; 2 | 3 | public class KotlinFromJava { 4 | public void test() { 5 | Chapter4.cube(3); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Chapter02/src/main/java/com/packt/chapter4/OverloadsForDefaults.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class OverloadsForDefaults { 4 | 5 | public String join(String[] array) { 6 | return join(array, ""); 7 | } 8 | 9 | public String join(String[] array, String prefix) { 10 | return join(array, prefix, ""); 11 | } 12 | 13 | public String join(String[] array, String prefix, String separator) { 14 | return join(array, prefix, separator, ""); 15 | } 16 | 17 | public String join(String[] array, String prefix, String separator, String suffix) { 18 | return null; // actual impl 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter02/src/main/java/com/packt/chapter4/ThrowsFromJava.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class ThrowsFromJava { 7 | public void test() { 8 | try { 9 | Chapter4.createDirectory(new File("mobydick.txt")); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/JavaCast.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaCast { 4 | 5 | public void printStringLength(Object obj) { 6 | if (obj instanceof String) { 7 | String str = (String) obj; 8 | System.out.print(str.length()); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/JavaIf.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaIf { 4 | 5 | public boolean isZero(int x) { 6 | boolean isZero; 7 | if (x == 0) 8 | isZero = true; 9 | else 10 | isZero = false; 11 | return isZero; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/array.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val array = arrayOf(1, 2, 3) 5 | 6 | val element1 = array[0] 7 | val element2 = array[1] 8 | array[2] = 5 9 | 10 | val perfectSquares = Array(10, { k -> k * k }) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/basic_syntax.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | var name = "kotlin" 5 | name = "more kotlin" 6 | val explicitType: Double = 12.3 7 | } 8 | 9 | fun returnValueIsInferred(x: Int) = x + 1 10 | 11 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/bitwise.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | val leftShift = 1 shl 2 6 | val rightShift = 1 shr 2 7 | val unsignedRightShift = 1 ushr 2 8 | 9 | val and = 1 and 0x00001111 10 | val or = 1 and 0x00001111 11 | val xor = 1 xor 0x00001111 12 | val inv = 1.inv() 13 | } 14 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/boolean.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val x = 1 5 | val y = 2 6 | val z = 2 7 | val isTrue = x < y && x < z 8 | val alsoTrue = x == y || y == z 9 | } 10 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/char.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val chars = arrayOf('\t', '\b', '\n', '\r', '\'', '\"', '\\', '\$') 4 | 5 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/col1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun col1() { 4 | val list = listOf(1, 2, 3, 4) 5 | for (k in list) { 6 | println(k) 7 | } 8 | 9 | val set = setOf(1, 2, 3, 4) 10 | for (k in set) { 11 | println(k) 12 | } 13 | } 14 | 15 | fun colrange() { 16 | val oneToTen = 1..10 17 | for (k in oneToTen) { 18 | for (j in 1..5) { 19 | println(k * j) 20 | } 21 | } 22 | } 23 | 24 | fun stringcol() { 25 | for (char in "string") { 26 | println(char) 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/comments.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | // line comment 6 | 7 | /* 8 | A block comment 9 | can span many 10 | lines 11 | */ 12 | } 13 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/controlflowasexpression.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.util.* 5 | 6 | fun expression() { 7 | "hello".startsWith("h") 8 | } 9 | 10 | fun statement() { 11 | val a = 1 12 | } 13 | 14 | fun isZero(x: Int): Boolean { 15 | return if (x == 0) true else false 16 | } 17 | 18 | fun c1() { 19 | val date = Date() 20 | val today = if (date.year == 2016) true else false 21 | } 22 | 23 | fun t1() { 24 | fun readFile() = {} 25 | val success = try { 26 | readFile() 27 | true 28 | } catch (e: IOException) { 29 | false 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/equals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | 5 | fun eq1() { 6 | val a = File("/mobydick.doc") 7 | val b = File("/mobydick.doc") 8 | val isFalse = a === b 9 | val isTrue = a !== b 10 | } 11 | 12 | fun eq2() { 13 | val a = File("/mobydick.doc") 14 | val b = File("/mobydick.doc") 15 | val isTrue = a == b 16 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.nio.file.Files 5 | import java.nio.file.Path 6 | 7 | class File(path: String) { 8 | fun close(): Unit { 9 | } 10 | } 11 | 12 | fun openFile(): File = File("") 13 | fun readFromFile(file: File): Unit { 14 | } 15 | 16 | fun readFile(path: Path): Unit { 17 | val input = Files.newInputStream(path) 18 | try { 19 | var byte = input.read() 20 | while (byte != -1) { 21 | println(byte) 22 | byte = input.read() 23 | } 24 | } catch (e: IOException) { 25 | println("Error reading from file. Error was ${e.message}") 26 | } finally { 27 | input.close() 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/explicitWidening.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = int.toLong() 6 | 7 | val float = 12.34F 8 | val double = float.toDouble() 9 | } 10 | 11 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/forloop.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun stringIteration(string: String) { 4 | for (char in string) { 5 | println(char) 6 | } 7 | } 8 | 9 | fun arrayIndices(array: Array) { 10 | for (index in array.indices) { 11 | println("Element $index is ${array[index]}") 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/literals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = 123456L 6 | val double = 12.34 7 | val float = 12.34F 8 | val hexadecimal = 0xAB 9 | val binary = 0b01010101 10 | } 11 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/new.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | import java.math.BigDecimal 5 | import java.time.LocalDate 6 | import java.util.* 7 | 8 | fun new() { 9 | val file = File("/etc/nginx/nginx.conf") 10 | val date = BigDecimal(100) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/null.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun isNull(str: String?): Boolean = if (str == null) true else false 4 | 5 | fun foo() { 6 | var str: String? 7 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/package.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Foo 4 | 5 | fun bar(): String = "bar" -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/private.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person2 { 4 | private fun age(): Int = 21 5 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/range1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun r1() { 4 | val aToZ = "a".."z" 5 | val isTrue = "c" in aToZ 6 | 7 | val oneToNine = 1..9 8 | val isFalse = 11 in oneToNine 9 | 10 | val countingDown = 100.downTo(0) 11 | val rangeTo = 10.rangeTo(20) 12 | 13 | val oneToFifty = 1..50 14 | val oddNumbers = oneToFifty.step(2) 15 | 16 | val countingDownEvenNumbers = (2..100).step(2).reversed() 17 | 18 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/return.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import com.sun.org.apache.xml.internal.security.Init 4 | 5 | fun addTwoNumbers(a: Int, b: Int): Int { 6 | return a + b 7 | } 8 | 9 | fun largestNumber(a: Int, b: Int, c: Int): Int { 10 | fun largest(a: Int, b: Int): Int { 11 | if (a > b) return a 12 | else return b 13 | } 14 | return largest(largest(a, b), largest(b, c)) 15 | } 16 | 17 | fun printLessThanTwo() { 18 | val list = listOf(1, 2, 3, 4) 19 | list.forEach(fun(x) { 20 | if (x < 2) println(x) 21 | else return 22 | }) 23 | println("This line will still execute") 24 | } 25 | 26 | fun printUntilStop1() { 27 | val list = listOf("a", "b", "stop", "c") 28 | list.forEach stop@ { 29 | if (it == "stop") return@stop 30 | else println(it) 31 | } 32 | } 33 | 34 | fun printUntilStop2() { 35 | val list = listOf("a", "b", "stop", "c") 36 | list.forEach { 37 | if (it == "stop") return@forEach 38 | else println(it) 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/smartcasts.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun printStringLength(any: Any) { 4 | if (any is String) { 5 | println(any.length) 6 | } 7 | } 8 | 9 | 10 | fun isString(any: Any): Boolean { 11 | return if (any is String) true else false 12 | } 13 | 14 | fun isEmptyString(any: Any): Boolean { 15 | return any is String && any.length == 0 16 | } 17 | 18 | fun isNotStringOrEmpty(any: Any): Boolean { 19 | return any !is String || any.length == 0 20 | } 21 | 22 | fun length(any: Any): Int { 23 | val string = any as String 24 | return string.length 25 | } 26 | 27 | fun safeCast() { 28 | val any = "/home/users" 29 | val string: String? = any as String 30 | val file: File? = any as File 31 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/string.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val string = "string with \n new line" 4 | 5 | val rawString = """ 6 | raw string is super useful for 7 | strings that span many lines 8 | """ -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/stringconcat.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun a() { 4 | val name = "Sam" 5 | val concat = "hello " + name 6 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/stringtemplate.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun st() { 4 | val name = "Sam" 5 | val str = "hello $name. Your name has ${name.length} characters" 6 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/this.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person(name: String) { 4 | fun printMe() = println(this) 5 | } 6 | 7 | class Building(val address: String) { 8 | inner class Reception(telephone: String) { 9 | fun printMyAddress() = println(this@Building.address) 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter2/while.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun wh() { 4 | while (true) { 5 | println("This will print out for a long time!") 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.1.kt: -------------------------------------------------------------------------------- 1 | fun concat1(a: String, b: String) = a + b 2 | 3 | fun concat2(a: String, b: String): String { 4 | return a + b 5 | } 6 | 7 | fun print1(str: String): Unit { 8 | println(str) 9 | } 10 | 11 | fun print2(str: String) { 12 | println(str) 13 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.10.kt: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal 2 | 3 | class InfixExample { 4 | infix fun concat(other:String) = this.toString() + other 5 | } 6 | 7 | fun standalone() { 8 | val sum = 1 + 2 9 | 10 | val account = Account() 11 | account.add(100.00) 12 | 13 | val account2 = InfixAccount() 14 | account2 add 100.00 15 | } 16 | 17 | 18 | class Account { 19 | var balance = 0.0 20 | fun add(amount: Double): Unit { 21 | this.balance = balance + amount 22 | } 23 | } 24 | 25 | 26 | class InfixAccount { 27 | var balance = 0.0 28 | infix fun add(amount: Double): Unit { 29 | this.balance = balance + amount 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.12.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | val printHello = { println("hello") } 4 | printHello() 5 | 6 | val printMessage = { message: String -> println(message) } 7 | 8 | printMessage("hello") 9 | 10 | 11 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.13.kt: -------------------------------------------------------------------------------- 1 | fun fib(k: Int): Int = when (k) { 2 | 0 -> 1 3 | 1 -> 1 4 | else -> fib(k - 1) + fib(k - 2) 5 | } 6 | 7 | fun fact(k: Int): Int { 8 | if (k == 0) return 1 9 | else return k * fact(k - 1) 10 | } 11 | 12 | fun fact2(k: Int): Int { 13 | tailrec fun factTail(m: Int, n: Int): Int { 14 | if (m == 0) return n 15 | else return factTail(m - 1, m * n) 16 | } 17 | return factTail(k, 1) 18 | } 19 | 20 | fun main(args: Array) { 21 | for (k in 1..10) { 22 | println(fact(k)) 23 | println(fact2(k)) 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.14.vararg.kt: -------------------------------------------------------------------------------- 1 | fun multiprint(vararg strings: String): Unit { 2 | for (string in strings) 3 | println(strings) 4 | } 5 | 6 | fun multiprint2(prefix: String, vararg strings: String): Unit { 7 | println(prefix) 8 | for (string in strings) 9 | println(string) 10 | } 11 | 12 | fun multiprint3(prefix: String, vararg strings: String, suffix: String): Unit { 13 | println(prefix) 14 | for (string in strings) 15 | println(string) 16 | println(suffix) 17 | } 18 | 19 | fun varargusage() { 20 | multiprint("a", "b", "c") 21 | multiprint2("Letters", "a", "b", "c", "Finished") 22 | multiprint3("Start", "a", "b", "c", suffix = "End") 23 | } 24 | 25 | fun spreadexample() { 26 | val strings = arrayOf("a", "b", "c", "d", "e") 27 | multiprint3("Start", *strings, suffix = "End") 28 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.16.genericfuncs.kt: -------------------------------------------------------------------------------- 1 | import com.sksamuel.book.new 2 | import java.util.* 3 | 4 | fun printRepeated(t: T, k: Int): Unit { 5 | for (x in 0..k) { 6 | println(t) 7 | } 8 | } 9 | 10 | fun choose(t1: T, t2: T, t3: T): T { 11 | return when (Random().nextInt(3)) { 12 | 0 -> t1 13 | 1 -> t2 14 | else -> t3 15 | } 16 | } 17 | 18 | fun generics() { 19 | val random = choose(5, 7, 9) 20 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.17.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicInteger 2 | 3 | val counter = AtomicInteger(1) 4 | 5 | fun unpure(k: Int): Int { 6 | return counter.incrementAndGet() + k 7 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.2.kt: -------------------------------------------------------------------------------- 1 | fun square(k: Int) = k * k 2 | 3 | fun square2(k: Int): Int = k * k 4 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.20.kt: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Named 2 | import java.util.concurrent.Executors 3 | import kotlin.concurrent.thread 4 | 5 | fun getters() { 6 | val named = Named() 7 | println("My name is " + named.name) 8 | named.name = "new name" 9 | } 10 | 11 | fun sams() { 12 | val threadPool = Executors.newFixedThreadPool(4) 13 | threadPool.submit { 14 | println("I don't have a lot of work to do") 15 | } 16 | 17 | threadPool.submit(object : Runnable { 18 | override fun run() { 19 | println("I don't have a lot of work to do") 20 | } 21 | }) 22 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.22.kotlin_from_java.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("Chapter4") 2 | 3 | package com.packt.chapter4 4 | 5 | import java.io.File 6 | import java.io.IOException 7 | 8 | fun cube(n: Int): Int = n * n * n 9 | 10 | @JvmOverloads fun join(array: Array, 11 | prefix: String = "", 12 | separator: String = "", 13 | suffix: String = ""): String { 14 | return "" 15 | } 16 | 17 | @Throws(IOException::class) 18 | fun createDirectory(file: File) { 19 | if (file.exists()) 20 | throw IOException("Directory already exists") 21 | file.createNewFile() 22 | } 23 | 24 | object Erasure { 25 | fun println(array: Array): Unit {} 26 | fun println(array: Array) : Unit {} 27 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.3.kt: -------------------------------------------------------------------------------- 1 | fun hello(): String = "hello world" 2 | 3 | fun hello(name: String): String = "hello to you $name" 4 | 5 | fun invocation() { 6 | val string = "hello" 7 | val length = string.take(5) 8 | } 9 | 10 | object Square { 11 | 12 | fun printArea(width: Int, height: Int): Unit { 13 | val area = calculateArea(width, height) 14 | println("The area is $area") 15 | } 16 | 17 | fun calculateArea(width: Int, height: Int): Int { 18 | return width * height 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.5.kt: -------------------------------------------------------------------------------- 1 | fun foo(k: Int) { 2 | require(k > 10, { "k should be greater than 10" }) 3 | println(k) 4 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.6.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | 4 | val string = "a kindness of ravens" 5 | string.regionMatches(14, "Red Ravens", 4, 6, true) 6 | 7 | string.regionMatches(thisOffset = 14, other = "Red Ravens", otherOffset = 4, length = 6, ignoreCase = true) 8 | 9 | fun deleteFiles(filePattern: String, recursive: Boolean, ignoreCase: Boolean, deleteDirectories: Boolean): Unit { 10 | 11 | } 12 | 13 | deleteFiles("*.jpg", true, true, false) 14 | 15 | deleteFiles("*.jpg", recursive = true, ignoreCase = true, deleteDirectories = false) 16 | 17 | deleteFiles(filePattern = "*.jpg", deleteDirectories = false, ignoreCase = true, recursive = true) 18 | 19 | string.endsWith(suffix = "ravens", ignoreCase = true) 20 | 21 | string.endsWith(ignoreCase = true, suffix = "ravens") 22 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/4.9.kt: -------------------------------------------------------------------------------- 1 | fun positiveRoot(k: Int): Double { 2 | require(k >= 0) 3 | return Math.sqrt(k.toDouble()) 4 | } 5 | 6 | fun negativeRoot(k: Int): Double { 7 | require(k >= 0) 8 | return -Math.sqrt(k.toDouble()) 9 | } 10 | 11 | fun roots(k: Int): Array { 12 | require(k >= 0) 13 | val root = Math.sqrt(k.toDouble()) 14 | return arrayOf(root, -root) 15 | } 16 | 17 | class Roots(pos: Double, neg: Double) 18 | 19 | fun roots2(k: Int): Roots { 20 | require(k >= 0) 21 | val root = Math.sqrt(k.toDouble()) 22 | return Roots(root, -root) 23 | } 24 | 25 | fun roots3(k: Int): Pair { 26 | require(k >= 0) 27 | val root = Math.sqrt(k.toDouble()) 28 | return Pair(root, -root) 29 | } 30 | 31 | fun main() { 32 | val (pos, neg) = roots3(16) 33 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Matrix { 4 | 5 | public Matrix plus(Matrix other) { 6 | return null; 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/Named.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Named { 4 | 5 | private String name; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/infix.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | class Age(val value: Int) { 4 | infix fun max(other: Age): Age = if (value > other.value) this else other 5 | } 6 | 7 | fun foo() { 8 | val sam = Age(37) 9 | val stef = Age(36) 10 | val oldest = sam max stef 11 | } 12 | 13 | fun toVsPair() { 14 | 15 | val pair1 = Pair("london", "uk") 16 | val pair2 = "london" to "uk" 17 | 18 | val map1 = mapOf(Pair("London", "UK"), Pair("Bucharest", "Romania")) 19 | val map2 = mapOf("London" to "UK", "Bucharest" to "Romania") 20 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/matrix.kt: -------------------------------------------------------------------------------- 1 | class TwoByTwoMatrix(val a: Int, val b: Int, val c: Int, val d: Int) { 2 | operator fun plus(matrix: TwoByTwoMatrix): TwoByTwoMatrix = 3 | TwoByTwoMatrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) 4 | } 5 | 6 | fun test() { 7 | val m1 = TwoByTwoMatrix(1, 2, 3, 4) 8 | val m2 = TwoByTwoMatrix(5, 6, 7, 8) 9 | val m3 = m1 + m2 10 | } 11 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter4/singlexpfun.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | fun square(k: Int) = k * k 4 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.10.Memoization.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ConcurrentHashMap 2 | 3 | fun main(args: Array) { 4 | val memfib = memoize(::fib) 5 | val qqq = ::fib.memoized() 6 | for (k in 1..1000) { 7 | val start = System.currentTimeMillis() 8 | val result = memfib(k) 9 | val end = System.currentTimeMillis() 10 | val duration = end - start 11 | println("fib($k)=$result took $duration ms") 12 | } 13 | } 14 | 15 | val map = mutableMapOf() 16 | 17 | fun memfib(k: Int): Long { 18 | return map.getOrPut(k) { 19 | when (k) { 20 | 0 -> 1 21 | 1 -> 1 22 | else -> memfib(k - 1) + memfib(k - 2) 23 | } 24 | } 25 | } 26 | 27 | fun memoize(fn: (A) -> R): (A) -> R { 28 | val map = ConcurrentHashMap() 29 | return { a -> 30 | map.getOrPut(a) { 31 | fn(a) 32 | } 33 | } 34 | } 35 | 36 | fun Function1.memoized(): (A) -> R { 37 | val map = ConcurrentHashMap() 38 | return { a -> 39 | map.getOrPut(a) { 40 | this.invoke(a) 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.2.Closures.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | import java.util.concurrent.Executors 4 | import java.util.concurrent.atomic.AtomicInteger 5 | 6 | fun paramClosure() { 7 | 8 | class Student(val firstName: String, val lastName: String) 9 | 10 | // accesses database to load student values 11 | fun loadStudents(): List = TODO() 12 | 13 | fun students(lastName: String): List { 14 | val regex = ".*$lastName.*".toRegex() 15 | return loadStudents().filter { it.lastName.matches(regex) } 16 | } 17 | } 18 | 19 | fun localValClosure() { 20 | val counter = AtomicInteger(0) 21 | val cores = Runtime.getRuntime().availableProcessors() 22 | val threadPool = Executors.newFixedThreadPool(cores) 23 | threadPool.submit { 24 | println("I am thread number ${counter.incrementAndGet()}") 25 | } 26 | } 27 | 28 | fun mutateClosure() { 29 | var containsNegative = false 30 | val ints = listOf(0, 1, 2, 3, 4, 5) 31 | ints.forEach { 32 | if (it < 0) 33 | containsNegative = true 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.3.Anonymous.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun shortfun() { 4 | listOf(1, 2, 3).filter { it > 1 } 5 | } 6 | 7 | fun anonymousFunctions() { 8 | fun(a: String, b: String): String = a + b 9 | 10 | val ints = listOf(1, 2, 3) 11 | val evens = ints.filter(fun(k: Int) = k % 2 == 0) 12 | 13 | val evens2 = ints.filter(fun(k) = k % 2 == 0) 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.5.Receivers.kt: -------------------------------------------------------------------------------- 1 | fun foo(fn: String.() -> Boolean): Unit { 2 | "string".fn() 3 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.7.Composition.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun compose2(fn1: (A) -> B, fn2: (B) -> C): (A) -> C = { a -> 4 | val b = fn1(a) 5 | val c = fn2(b) 6 | c 7 | } 8 | 9 | fun composeExample() { 10 | 11 | val f = String::length 12 | val g = Any::hashCode 13 | val fog = compose2(f, g) 14 | println(fog("what is the hash of my length?")) 15 | 16 | } 17 | 18 | infix fun Function1.compose(fn: (R) -> R2): (P1) -> R2 = { 19 | fn(this(it)) 20 | } 21 | 22 | fun infixexample() { 23 | val f = String::length 24 | val g = Any::hashCode 25 | val fog = f compose g 26 | } 27 | 28 | operator infix fun Function1.times(fn: (R) -> R2): (P1) -> R2 = { 29 | fn(this(it)) 30 | } 31 | 32 | fun opexample() { 33 | val f = String::length 34 | val g = Any::hashCode 35 | val fog = f * g 36 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/chapter5/5.9.Currying.kt: -------------------------------------------------------------------------------- 1 | import java.util.logging.Level 2 | 3 | fun Function2.curried(): (P1) -> (P2) -> R = 4 | { p1 -> 5 | { p2 -> 6 | this(p1, p2) 7 | } 8 | } 9 | 10 | fun Function3.curried(): (P1) -> (P2) -> (P3) -> R = 11 | { p1 -> 12 | { p2 -> 13 | { p3 -> 14 | this(p1, p2, p3) 15 | } 16 | } 17 | } 18 | 19 | fun logger(level: Level, appender: Appendable, msg: String): Nothing = TODO() 20 | 21 | fun curryExample() { 22 | val logger: (Level) -> (Appendable) -> (String) -> Unit = ::logger.curried() 23 | val logger2: (Appendable) -> (String) -> Unit = logger(Level.SEVERE) 24 | val logger3: (String) -> Unit = logger2(System.out) 25 | logger3("my message") 26 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/myproject/constants/import1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject.constants 2 | 3 | val PI = 3.142 4 | val E = 2.178 5 | 6 | class Foo -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/myproject/import2.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject 2 | 3 | import com.packt.myproject.Foo 4 | import com.packt.otherproject.Foo as Foo2 5 | 6 | fun doubleFoo() { 7 | val foo1 = Foo() 8 | val foo2 = Foo2() 9 | } -------------------------------------------------------------------------------- /Chapter02/src/main/kotlin/com/packt/otherproject/Foo.kt: -------------------------------------------------------------------------------- 1 | package com.packt.otherproject 2 | 3 | class Foo -------------------------------------------------------------------------------- /Chapter03/inheritance/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Chapter03/inheritance/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter03/inheritance/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'inheritance' 2 | 3 | -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/A.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | abstract class A { 4 | abstract fun doSomething() 5 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Abstract.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import java.util.* 4 | 5 | open class AParent protected constructor() { 6 | open fun someMethod(): Int = Random().nextInt() 7 | } 8 | 9 | abstract class DDerived : AParent() { 10 | abstract override fun someMethod(): Int 11 | } 12 | 13 | class AlwaysOne : DDerived() { 14 | override fun someMethod(): Int { 15 | return 1 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Airplane.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | interface Airplane { 4 | fun fly(): Unit 5 | } 6 | 7 | 8 | abstract class SingleEngineAirplane protected constructor() { 9 | abstract fun fly() 10 | } 11 | 12 | class CesanaAirplane : SingleEngineAirplane() { 13 | final override fun fly() { 14 | println("Flying a cesna") 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/AmphibiousCar.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | interface Drivable { 4 | fun drive() 5 | } 6 | 7 | interface Sailable { 8 | fun saill() 9 | } 10 | 11 | class AmphibiousCar(val name: String) : Drivable, Sailable { 12 | override fun drive() { 13 | println("Driving...") 14 | } 15 | 16 | override fun saill() { 17 | println("Sailling...") 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Base.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | open class BaseA { 4 | open val property1: String 5 | get() = "Base::value" 6 | 7 | } 8 | 9 | class Derived1 : BaseA() { 10 | override val property1: String 11 | get() = "Derived::value" 12 | } 13 | 14 | class Derived2(override val property1: String) : BaseA() {} 15 | 16 | 17 | open class BaseB(open val propertyFoo: String) { 18 | } 19 | 20 | class DerivedB : BaseB("") { 21 | private var _propFoo: String = "" 22 | override var propertyFoo: String 23 | get() = _propFoo 24 | set(value) { 25 | _propFoo = value 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/CardPayment.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import org.joda.time.DateTime 4 | import java.math.BigDecimal 5 | 6 | class CardPayment(amount: BigDecimal, val number: String, val expiryDate: DateTime, val type: CardType) : Payment(amount) -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/CardType.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | 4 | enum class CardType { 5 | VISA, MASTERCARD, AMEX 6 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/ChequePayment.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import java.math.BigDecimal 4 | 5 | class ChequePayment : Payment { 6 | constructor(amount: BigDecimal, name: String, bankId: String) : super(amount) { 7 | this.name = name 8 | this.bankId = bankId 9 | } 10 | 11 | var name: String 12 | get() = this.name 13 | 14 | var bankId: String 15 | get() = this.bankId 16 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Container.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | open class Container { 4 | protected open val fieldA: String = "Some value" 5 | } 6 | 7 | class DerivedContainer : Container() { 8 | public override val fieldA: String = "Something else" 9 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Document.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import java.io.InputStream 4 | 5 | interface IPersistable { 6 | fun save(stream: InputStream) 7 | } 8 | 9 | interface IPrintable { 10 | fun print(){ 11 | println("aaa") 12 | } 13 | } 14 | 15 | abstract class Document(val title: String) { 16 | 17 | } 18 | 19 | class TextDocument(title: String) : IPersistable, Document(title), IPrintable { 20 | override fun save(stream: InputStream) { 21 | println("Saving to input stream") 22 | } 23 | 24 | override fun print() { 25 | println("Document name:$title") 26 | } 27 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Image.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import java.io.OutputStream 4 | 5 | open class Image { 6 | open fun save(output: OutputStream) { 7 | println("Some logic to save an image") 8 | } 9 | } 10 | 11 | interface VendorImage { 12 | fun save(output: OutputStream) { 13 | println("Vendor saving an image") 14 | } 15 | } 16 | 17 | class PNGImage : Image(), VendorImage { 18 | override fun save(output: OutputStream) { 19 | super.save(output) 20 | super.save(output) 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/IntBinaryTreee.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | sealed class IntBinaryTree { 4 | class EmptyNode : IntBinaryTree() 5 | class IntBinaryTreeNode(val left: IntBinaryTree, val value: Int, val right: IntBinaryTree) : IntBinaryTree() 6 | } 7 | 8 | fun toCollection(tree: IntBinaryTree): Collection = 9 | when (tree) { 10 | is IntBinaryTree.EmptyNode -> emptyList() 11 | is IntBinaryTree.IntBinaryTreeNode -> toCollection(tree.left) + tree.value + toCollection(tree.right) 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Payment.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | import java.math.BigDecimal 4 | 5 | open class Payment(val amount: BigDecimal) -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Singleton.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | object Singleton{ 4 | private var count = 0 5 | ; 6 | fun doSomething():Unit { 7 | println("Calling a doSomething (${++count} call/-s in total)") 8 | } 9 | } 10 | 11 | open class SingletonParent(var x:Int){ 12 | fun something():Unit{ 13 | println("X=$x") 14 | } 15 | } 16 | 17 | object SingletonDerive:SingletonParent(10){ 18 | 19 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Static.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | fun showFirstCharacter(input:String):Char{ 4 | if(input.isEmpty()) throw IllegalArgumentException() 5 | return input.first() 6 | } -------------------------------------------------------------------------------- /Chapter03/inheritance/src/main/kotlin/com/programming/kotlin/chapter03/Student.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | interface StudentFactory { 4 | fun create(name: String): Student 5 | } 6 | 7 | class Student private constructor(val name: String) { 8 | companion object : StudentFactory { 9 | override fun create(name: String): Student { 10 | return Student(name) 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter03/polymorphism/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter03/polymorphism/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'polymorphism' 2 | 3 | -------------------------------------------------------------------------------- /Chapter03/polymorphism/src/main/kotlin/com/programming/kotlin/chapter03/Ellipsis.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | class Ellipsis : Shape() { 4 | 5 | override fun isHit(x: Int, y: Int): Boolean { 6 | val xRadius = Width.toDouble() / 2 7 | val yRadius = Height.toDouble() / 2 8 | 9 | val centerX = XLocation + xRadius 10 | val centerY = YLocation + yRadius 11 | 12 | if (xRadius == 0.0 || yRadius == 0.0) 13 | return false 14 | 15 | 16 | val normalizedX = centerX - XLocation 17 | val normalizedY = centerY - YLocation 18 | 19 | return (normalizedX * normalizedX) / (xRadius * xRadius) + (normalizedY * normalizedY) / (yRadius * yRadius) <= 1.0 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter03/polymorphism/src/main/kotlin/com/programming/kotlin/chapter03/Program.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | fun main(args: Array) { 4 | 5 | val e1 = Ellipsis() 6 | e1.Height = 10 7 | e1.Width = 12 8 | 9 | val e2 = Ellipsis() 10 | e2.XLocation = 100 11 | e2.YLocation = 96 12 | e1.Height = 21 13 | e1.Width = 19 14 | 15 | val r1 = Rectangular() 16 | r1.XLocation = 49 17 | r1.YLocation = 45 18 | r1.Width = 10 19 | r1.Height = 10 20 | 21 | val shapes = listOf(e1, e2, r1) 22 | 23 | val selected:Shape? = shapes.firstOrNull { shape -> 24 | shape.isHit(50, 52) 25 | } 26 | 27 | if(selected == null){ 28 | println("There is no shape at point(50,52)") 29 | }else{ 30 | println("A shape of type ${selected.javaClass.simpleName} has been selected.") 31 | } 32 | } -------------------------------------------------------------------------------- /Chapter03/polymorphism/src/main/kotlin/com/programming/kotlin/chapter03/Rectangular.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | class Rectangular : Shape() { 4 | override fun isHit(x: Int, y: Int): Boolean { 5 | return x >= XLocation && x <= (XLocation + Width) && y >= YLocation && y <= YLocation + Height 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter03/polymorphism/src/main/kotlin/com/programming/kotlin/chapter03/Shape.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter03 2 | 3 | abstract class Shape protected constructor() { 4 | private var _xLocation:Int = 0 5 | private var _yLocation:Int = 0 6 | private var _width:Int = 0 7 | private var _height:Int = 0 8 | 9 | var XLocation: Int 10 | get() = this._xLocation 11 | set(value: Int) { 12 | this._xLocation = value 13 | } 14 | 15 | var YLocation: Int 16 | get() = this._yLocation 17 | set(value: Int) { 18 | this._yLocation = value 19 | } 20 | 21 | var Width: Int 22 | get() = this._width 23 | set(value: Int) { 24 | this._width = value 25 | } 26 | 27 | var Height: Int 28 | get() = this._height 29 | set(value: Int) { 30 | this._height = value 31 | } 32 | 33 | abstract fun isHit(x: Int, y: Int): Boolean 34 | 35 | } -------------------------------------------------------------------------------- /Chapter04/src/main/java/KotlinFromJava.java: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Chapter4; 2 | 3 | public class KotlinFromJava { 4 | public void test() { 5 | Chapter4.cube(3); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Chapter04/src/main/java/com/packt/chapter4/OverloadsForDefaults.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class OverloadsForDefaults { 4 | 5 | public String join(String[] array) { 6 | return join(array, ""); 7 | } 8 | 9 | public String join(String[] array, String prefix) { 10 | return join(array, prefix, ""); 11 | } 12 | 13 | public String join(String[] array, String prefix, String separator) { 14 | return join(array, prefix, separator, ""); 15 | } 16 | 17 | public String join(String[] array, String prefix, String separator, String suffix) { 18 | return null; // actual impl 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter04/src/main/java/com/packt/chapter4/ThrowsFromJava.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class ThrowsFromJava { 7 | public void test() { 8 | try { 9 | Chapter4.createDirectory(new File("mobydick.txt")); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/JavaCast.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaCast { 4 | 5 | public void printStringLength(Object obj) { 6 | if (obj instanceof String) { 7 | String str = (String) obj; 8 | System.out.print(str.length()); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/JavaIf.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaIf { 4 | 5 | public boolean isZero(int x) { 6 | boolean isZero; 7 | if (x == 0) 8 | isZero = true; 9 | else 10 | isZero = false; 11 | return isZero; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/array.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val array = arrayOf(1, 2, 3) 5 | 6 | val element1 = array[0] 7 | val element2 = array[1] 8 | array[2] = 5 9 | 10 | val perfectSquares = Array(10, { k -> k * k }) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/basic_syntax.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | var name = "kotlin" 5 | name = "more kotlin" 6 | val explicitType: Double = 12.3 7 | } 8 | 9 | fun returnValueIsInferred(x: Int) = x + 1 10 | 11 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/bitwise.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | val leftShift = 1 shl 2 6 | val rightShift = 1 shr 2 7 | val unsignedRightShift = 1 ushr 2 8 | 9 | val and = 1 and 0x00001111 10 | val or = 1 and 0x00001111 11 | val xor = 1 xor 0x00001111 12 | val inv = 1.inv() 13 | } 14 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/boolean.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val x = 1 5 | val y = 2 6 | val z = 2 7 | val isTrue = x < y && x < z 8 | val alsoTrue = x == y || y == z 9 | } 10 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/char.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val chars = arrayOf('\t', '\b', '\n', '\r', '\'', '\"', '\\', '\$') 4 | 5 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/col1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun col1() { 4 | val list = listOf(1, 2, 3, 4) 5 | for (k in list) { 6 | println(k) 7 | } 8 | 9 | val set = setOf(1, 2, 3, 4) 10 | for (k in set) { 11 | println(k) 12 | } 13 | } 14 | 15 | fun colrange() { 16 | val oneToTen = 1..10 17 | for (k in oneToTen) { 18 | for (j in 1..5) { 19 | println(k * j) 20 | } 21 | } 22 | } 23 | 24 | fun stringcol() { 25 | for (char in "string") { 26 | println(char) 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/comments.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | // line comment 6 | 7 | /* 8 | A block comment 9 | can span many 10 | lines 11 | */ 12 | } 13 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/controlflowasexpression.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.util.* 5 | 6 | fun expression() { 7 | "hello".startsWith("h") 8 | } 9 | 10 | fun statement() { 11 | val a = 1 12 | } 13 | 14 | fun isZero(x: Int): Boolean { 15 | return if (x == 0) true else false 16 | } 17 | 18 | fun c1() { 19 | val date = Date() 20 | val today = if (date.year == 2016) true else false 21 | } 22 | 23 | fun t1() { 24 | fun readFile() = {} 25 | val success = try { 26 | readFile() 27 | true 28 | } catch (e: IOException) { 29 | false 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/equals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | 5 | fun eq1() { 6 | val a = File("/mobydick.doc") 7 | val b = File("/mobydick.doc") 8 | val isFalse = a === b 9 | val isTrue = a !== b 10 | } 11 | 12 | fun eq2() { 13 | val a = File("/mobydick.doc") 14 | val b = File("/mobydick.doc") 15 | val isTrue = a == b 16 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.nio.file.Files 5 | import java.nio.file.Path 6 | 7 | class File(path: String) { 8 | fun close(): Unit { 9 | } 10 | } 11 | 12 | fun openFile(): File = File("") 13 | fun readFromFile(file: File): Unit { 14 | } 15 | 16 | fun readFile(path: Path): Unit { 17 | val input = Files.newInputStream(path) 18 | try { 19 | var byte = input.read() 20 | while (byte != -1) { 21 | println(byte) 22 | byte = input.read() 23 | } 24 | } catch (e: IOException) { 25 | println("Error reading from file. Error was ${e.message}") 26 | } finally { 27 | input.close() 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/explicitWidening.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = int.toLong() 6 | 7 | val float = 12.34F 8 | val double = float.toDouble() 9 | } 10 | 11 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/forloop.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun stringIteration(string: String) { 4 | for (char in string) { 5 | println(char) 6 | } 7 | } 8 | 9 | fun arrayIndices(array: Array) { 10 | for (index in array.indices) { 11 | println("Element $index is ${array[index]}") 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/literals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = 123456L 6 | val double = 12.34 7 | val float = 12.34F 8 | val hexadecimal = 0xAB 9 | val binary = 0b01010101 10 | } 11 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/new.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | import java.math.BigDecimal 5 | import java.time.LocalDate 6 | import java.util.* 7 | 8 | fun new() { 9 | val file = File("/etc/nginx/nginx.conf") 10 | val date = BigDecimal(100) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/null.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun isNull(str: String?): Boolean = if (str == null) true else false 4 | 5 | fun foo() { 6 | var str: String? 7 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/package.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Foo 4 | 5 | fun bar(): String = "bar" -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/private.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person2 { 4 | private fun age(): Int = 21 5 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/range1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun r1() { 4 | val aToZ = "a".."z" 5 | val isTrue = "c" in aToZ 6 | 7 | val oneToNine = 1..9 8 | val isFalse = 11 in oneToNine 9 | 10 | val countingDown = 100.downTo(0) 11 | val rangeTo = 10.rangeTo(20) 12 | 13 | val oneToFifty = 1..50 14 | val oddNumbers = oneToFifty.step(2) 15 | 16 | val countingDownEvenNumbers = (2..100).step(2).reversed() 17 | 18 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/return.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import com.sun.org.apache.xml.internal.security.Init 4 | 5 | fun addTwoNumbers(a: Int, b: Int): Int { 6 | return a + b 7 | } 8 | 9 | fun largestNumber(a: Int, b: Int, c: Int): Int { 10 | fun largest(a: Int, b: Int): Int { 11 | if (a > b) return a 12 | else return b 13 | } 14 | return largest(largest(a, b), largest(b, c)) 15 | } 16 | 17 | fun printLessThanTwo() { 18 | val list = listOf(1, 2, 3, 4) 19 | list.forEach(fun(x) { 20 | if (x < 2) println(x) 21 | else return 22 | }) 23 | println("This line will still execute") 24 | } 25 | 26 | fun printUntilStop1() { 27 | val list = listOf("a", "b", "stop", "c") 28 | list.forEach stop@ { 29 | if (it == "stop") return@stop 30 | else println(it) 31 | } 32 | } 33 | 34 | fun printUntilStop2() { 35 | val list = listOf("a", "b", "stop", "c") 36 | list.forEach { 37 | if (it == "stop") return@forEach 38 | else println(it) 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/smartcasts.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun printStringLength(any: Any) { 4 | if (any is String) { 5 | println(any.length) 6 | } 7 | } 8 | 9 | 10 | fun isString(any: Any): Boolean { 11 | return if (any is String) true else false 12 | } 13 | 14 | fun isEmptyString(any: Any): Boolean { 15 | return any is String && any.length == 0 16 | } 17 | 18 | fun isNotStringOrEmpty(any: Any): Boolean { 19 | return any !is String || any.length == 0 20 | } 21 | 22 | fun length(any: Any): Int { 23 | val string = any as String 24 | return string.length 25 | } 26 | 27 | fun safeCast() { 28 | val any = "/home/users" 29 | val string: String? = any as String 30 | val file: File? = any as File 31 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/string.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val string = "string with \n new line" 4 | 5 | val rawString = """ 6 | raw string is super useful for 7 | strings that span many lines 8 | """ -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/stringconcat.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun a() { 4 | val name = "Sam" 5 | val concat = "hello " + name 6 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/stringtemplate.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun st() { 4 | val name = "Sam" 5 | val str = "hello $name. Your name has ${name.length} characters" 6 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/this.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person(name: String) { 4 | fun printMe() = println(this) 5 | } 6 | 7 | class Building(val address: String) { 8 | inner class Reception(telephone: String) { 9 | fun printMyAddress() = println(this@Building.address) 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter2/while.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun wh() { 4 | while (true) { 5 | println("This will print out for a long time!") 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.1.kt: -------------------------------------------------------------------------------- 1 | fun concat1(a: String, b: String) = a + b 2 | 3 | fun concat2(a: String, b: String): String { 4 | return a + b 5 | } 6 | 7 | fun print1(str: String): Unit { 8 | println(str) 9 | } 10 | 11 | fun print2(str: String) { 12 | println(str) 13 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.10.kt: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal 2 | 3 | class InfixExample { 4 | infix fun concat(other:String) = this.toString() + other 5 | } 6 | 7 | fun standalone() { 8 | val sum = 1 + 2 9 | 10 | val account = Account() 11 | account.add(100.00) 12 | 13 | val account2 = InfixAccount() 14 | account2 add 100.00 15 | } 16 | 17 | 18 | class Account { 19 | var balance = 0.0 20 | fun add(amount: Double): Unit { 21 | this.balance = balance + amount 22 | } 23 | } 24 | 25 | 26 | class InfixAccount { 27 | var balance = 0.0 28 | infix fun add(amount: Double): Unit { 29 | this.balance = balance + amount 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.12.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | val printHello = { println("hello") } 4 | printHello() 5 | 6 | val printMessage = { message: String -> println(message) } 7 | 8 | printMessage("hello") 9 | 10 | 11 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.13.kt: -------------------------------------------------------------------------------- 1 | fun fib(k: Int): Int = when (k) { 2 | 0 -> 1 3 | 1 -> 1 4 | else -> fib(k - 1) + fib(k - 2) 5 | } 6 | 7 | fun fact(k: Int): Int { 8 | if (k == 0) return 1 9 | else return k * fact(k - 1) 10 | } 11 | 12 | fun fact2(k: Int): Int { 13 | tailrec fun factTail(m: Int, n: Int): Int { 14 | if (m == 0) return n 15 | else return factTail(m - 1, m * n) 16 | } 17 | return factTail(k, 1) 18 | } 19 | 20 | fun main(args: Array) { 21 | for (k in 1..10) { 22 | println(fact(k)) 23 | println(fact2(k)) 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.14.vararg.kt: -------------------------------------------------------------------------------- 1 | fun multiprint(vararg strings: String): Unit { 2 | for (string in strings) 3 | println(strings) 4 | } 5 | 6 | fun multiprint2(prefix: String, vararg strings: String): Unit { 7 | println(prefix) 8 | for (string in strings) 9 | println(string) 10 | } 11 | 12 | fun multiprint3(prefix: String, vararg strings: String, suffix: String): Unit { 13 | println(prefix) 14 | for (string in strings) 15 | println(string) 16 | println(suffix) 17 | } 18 | 19 | fun varargusage() { 20 | multiprint("a", "b", "c") 21 | multiprint2("Letters", "a", "b", "c", "Finished") 22 | multiprint3("Start", "a", "b", "c", suffix = "End") 23 | } 24 | 25 | fun spreadexample() { 26 | val strings = arrayOf("a", "b", "c", "d", "e") 27 | multiprint3("Start", *strings, suffix = "End") 28 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.16.genericfuncs.kt: -------------------------------------------------------------------------------- 1 | import com.sksamuel.book.new 2 | import java.util.* 3 | 4 | fun printRepeated(t: T, k: Int): Unit { 5 | for (x in 0..k) { 6 | println(t) 7 | } 8 | } 9 | 10 | fun choose(t1: T, t2: T, t3: T): T { 11 | return when (Random().nextInt(3)) { 12 | 0 -> t1 13 | 1 -> t2 14 | else -> t3 15 | } 16 | } 17 | 18 | fun generics() { 19 | val random = choose(5, 7, 9) 20 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.17.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicInteger 2 | 3 | val counter = AtomicInteger(1) 4 | 5 | fun unpure(k: Int): Int { 6 | return counter.incrementAndGet() + k 7 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.2.kt: -------------------------------------------------------------------------------- 1 | fun square(k: Int) = k * k 2 | 3 | fun square2(k: Int): Int = k * k 4 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.20.kt: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Named 2 | import java.util.concurrent.Executors 3 | import kotlin.concurrent.thread 4 | 5 | fun getters() { 6 | val named = Named() 7 | println("My name is " + named.name) 8 | named.name = "new name" 9 | } 10 | 11 | fun sams() { 12 | val threadPool = Executors.newFixedThreadPool(4) 13 | threadPool.submit { 14 | println("I don't have a lot of work to do") 15 | } 16 | 17 | threadPool.submit(object : Runnable { 18 | override fun run() { 19 | println("I don't have a lot of work to do") 20 | } 21 | }) 22 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.22.kotlin_from_java.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("Chapter4") 2 | 3 | package com.packt.chapter4 4 | 5 | import java.io.File 6 | import java.io.IOException 7 | 8 | fun cube(n: Int): Int = n * n * n 9 | 10 | @JvmOverloads fun join(array: Array, 11 | prefix: String = "", 12 | separator: String = "", 13 | suffix: String = ""): String { 14 | return "" 15 | } 16 | 17 | @Throws(IOException::class) 18 | fun createDirectory(file: File) { 19 | if (file.exists()) 20 | throw IOException("Directory already exists") 21 | file.createNewFile() 22 | } 23 | 24 | object Erasure { 25 | fun println(array: Array): Unit {} 26 | fun println(array: Array) : Unit {} 27 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.3.kt: -------------------------------------------------------------------------------- 1 | fun hello(): String = "hello world" 2 | 3 | fun hello(name: String): String = "hello to you $name" 4 | 5 | fun invocation() { 6 | val string = "hello" 7 | val length = string.take(5) 8 | } 9 | 10 | object Square { 11 | 12 | fun printArea(width: Int, height: Int): Unit { 13 | val area = calculateArea(width, height) 14 | println("The area is $area") 15 | } 16 | 17 | fun calculateArea(width: Int, height: Int): Int { 18 | return width * height 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.5.kt: -------------------------------------------------------------------------------- 1 | fun foo(k: Int) { 2 | require(k > 10, { "k should be greater than 10" }) 3 | println(k) 4 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.6.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | 4 | val string = "a kindness of ravens" 5 | string.regionMatches(14, "Red Ravens", 4, 6, true) 6 | 7 | string.regionMatches(thisOffset = 14, other = "Red Ravens", otherOffset = 4, length = 6, ignoreCase = true) 8 | 9 | fun deleteFiles(filePattern: String, recursive: Boolean, ignoreCase: Boolean, deleteDirectories: Boolean): Unit { 10 | 11 | } 12 | 13 | deleteFiles("*.jpg", true, true, false) 14 | 15 | deleteFiles("*.jpg", recursive = true, ignoreCase = true, deleteDirectories = false) 16 | 17 | deleteFiles(filePattern = "*.jpg", deleteDirectories = false, ignoreCase = true, recursive = true) 18 | 19 | string.endsWith(suffix = "ravens", ignoreCase = true) 20 | 21 | string.endsWith(ignoreCase = true, suffix = "ravens") 22 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/4.9.kt: -------------------------------------------------------------------------------- 1 | fun positiveRoot(k: Int): Double { 2 | require(k >= 0) 3 | return Math.sqrt(k.toDouble()) 4 | } 5 | 6 | fun negativeRoot(k: Int): Double { 7 | require(k >= 0) 8 | return -Math.sqrt(k.toDouble()) 9 | } 10 | 11 | fun roots(k: Int): Array { 12 | require(k >= 0) 13 | val root = Math.sqrt(k.toDouble()) 14 | return arrayOf(root, -root) 15 | } 16 | 17 | class Roots(pos: Double, neg: Double) 18 | 19 | fun roots2(k: Int): Roots { 20 | require(k >= 0) 21 | val root = Math.sqrt(k.toDouble()) 22 | return Roots(root, -root) 23 | } 24 | 25 | fun roots3(k: Int): Pair { 26 | require(k >= 0) 27 | val root = Math.sqrt(k.toDouble()) 28 | return Pair(root, -root) 29 | } 30 | 31 | fun main() { 32 | val (pos, neg) = roots3(16) 33 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Matrix { 4 | 5 | public Matrix plus(Matrix other) { 6 | return null; 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/Named.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Named { 4 | 5 | private String name; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/infix.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | class Age(val value: Int) { 4 | infix fun max(other: Age): Age = if (value > other.value) this else other 5 | } 6 | 7 | fun foo() { 8 | val sam = Age(37) 9 | val stef = Age(36) 10 | val oldest = sam max stef 11 | } 12 | 13 | fun toVsPair() { 14 | 15 | val pair1 = Pair("london", "uk") 16 | val pair2 = "london" to "uk" 17 | 18 | val map1 = mapOf(Pair("London", "UK"), Pair("Bucharest", "Romania")) 19 | val map2 = mapOf("London" to "UK", "Bucharest" to "Romania") 20 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/matrix.kt: -------------------------------------------------------------------------------- 1 | class TwoByTwoMatrix(val a: Int, val b: Int, val c: Int, val d: Int) { 2 | operator fun plus(matrix: TwoByTwoMatrix): TwoByTwoMatrix = 3 | TwoByTwoMatrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) 4 | } 5 | 6 | fun test() { 7 | val m1 = TwoByTwoMatrix(1, 2, 3, 4) 8 | val m2 = TwoByTwoMatrix(5, 6, 7, 8) 9 | val m3 = m1 + m2 10 | } 11 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter4/singlexpfun.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | fun square(k: Int) = k * k 4 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.10.Memoization.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ConcurrentHashMap 2 | 3 | fun main(args: Array) { 4 | val memfib = memoize(::fib) 5 | val qqq = ::fib.memoized() 6 | for (k in 1..1000) { 7 | val start = System.currentTimeMillis() 8 | val result = memfib(k) 9 | val end = System.currentTimeMillis() 10 | val duration = end - start 11 | println("fib($k)=$result took $duration ms") 12 | } 13 | } 14 | 15 | val map = mutableMapOf() 16 | 17 | fun memfib(k: Int): Long { 18 | return map.getOrPut(k) { 19 | when (k) { 20 | 0 -> 1 21 | 1 -> 1 22 | else -> memfib(k - 1) + memfib(k - 2) 23 | } 24 | } 25 | } 26 | 27 | fun memoize(fn: (A) -> R): (A) -> R { 28 | val map = ConcurrentHashMap() 29 | return { a -> 30 | map.getOrPut(a) { 31 | fn(a) 32 | } 33 | } 34 | } 35 | 36 | fun Function1.memoized(): (A) -> R { 37 | val map = ConcurrentHashMap() 38 | return { a -> 39 | map.getOrPut(a) { 40 | this.invoke(a) 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.2.Closures.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | import java.util.concurrent.Executors 4 | import java.util.concurrent.atomic.AtomicInteger 5 | 6 | fun paramClosure() { 7 | 8 | class Student(val firstName: String, val lastName: String) 9 | 10 | // accesses database to load student values 11 | fun loadStudents(): List = TODO() 12 | 13 | fun students(lastName: String): List { 14 | val regex = ".*$lastName.*".toRegex() 15 | return loadStudents().filter { it.lastName.matches(regex) } 16 | } 17 | } 18 | 19 | fun localValClosure() { 20 | val counter = AtomicInteger(0) 21 | val cores = Runtime.getRuntime().availableProcessors() 22 | val threadPool = Executors.newFixedThreadPool(cores) 23 | threadPool.submit { 24 | println("I am thread number ${counter.incrementAndGet()}") 25 | } 26 | } 27 | 28 | fun mutateClosure() { 29 | var containsNegative = false 30 | val ints = listOf(0, 1, 2, 3, 4, 5) 31 | ints.forEach { 32 | if (it < 0) 33 | containsNegative = true 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.3.Anonymous.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun shortfun() { 4 | listOf(1, 2, 3).filter { it > 1 } 5 | } 6 | 7 | fun anonymousFunctions() { 8 | fun(a: String, b: String): String = a + b 9 | 10 | val ints = listOf(1, 2, 3) 11 | val evens = ints.filter(fun(k: Int) = k % 2 == 0) 12 | 13 | val evens2 = ints.filter(fun(k) = k % 2 == 0) 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.5.Receivers.kt: -------------------------------------------------------------------------------- 1 | fun foo(fn: String.() -> Boolean): Unit { 2 | "string".fn() 3 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.7.Composition.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun compose2(fn1: (A) -> B, fn2: (B) -> C): (A) -> C = { a -> 4 | val b = fn1(a) 5 | val c = fn2(b) 6 | c 7 | } 8 | 9 | fun composeExample() { 10 | 11 | val f = String::length 12 | val g = Any::hashCode 13 | val fog = compose2(f, g) 14 | println(fog("what is the hash of my length?")) 15 | 16 | } 17 | 18 | infix fun Function1.compose(fn: (R) -> R2): (P1) -> R2 = { 19 | fn(this(it)) 20 | } 21 | 22 | fun infixexample() { 23 | val f = String::length 24 | val g = Any::hashCode 25 | val fog = f compose g 26 | } 27 | 28 | operator infix fun Function1.times(fn: (R) -> R2): (P1) -> R2 = { 29 | fn(this(it)) 30 | } 31 | 32 | fun opexample() { 33 | val f = String::length 34 | val g = Any::hashCode 35 | val fog = f * g 36 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/chapter5/5.9.Currying.kt: -------------------------------------------------------------------------------- 1 | import java.util.logging.Level 2 | 3 | fun Function2.curried(): (P1) -> (P2) -> R = 4 | { p1 -> 5 | { p2 -> 6 | this(p1, p2) 7 | } 8 | } 9 | 10 | fun Function3.curried(): (P1) -> (P2) -> (P3) -> R = 11 | { p1 -> 12 | { p2 -> 13 | { p3 -> 14 | this(p1, p2, p3) 15 | } 16 | } 17 | } 18 | 19 | fun logger(level: Level, appender: Appendable, msg: String): Nothing = TODO() 20 | 21 | fun curryExample() { 22 | val logger: (Level) -> (Appendable) -> (String) -> Unit = ::logger.curried() 23 | val logger2: (Appendable) -> (String) -> Unit = logger(Level.SEVERE) 24 | val logger3: (String) -> Unit = logger2(System.out) 25 | logger3("my message") 26 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/myproject/constants/import1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject.constants 2 | 3 | val PI = 3.142 4 | val E = 2.178 5 | 6 | class Foo -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/myproject/import2.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject 2 | 3 | import com.packt.myproject.Foo 4 | import com.packt.otherproject.Foo as Foo2 5 | 6 | fun doubleFoo() { 7 | val foo1 = Foo() 8 | val foo2 = Foo2() 9 | } -------------------------------------------------------------------------------- /Chapter04/src/main/kotlin/com/packt/otherproject/Foo.kt: -------------------------------------------------------------------------------- 1 | package com.packt.otherproject 2 | 3 | class Foo -------------------------------------------------------------------------------- /Chapter05/src/main/java/KotlinFromJava.java: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Chapter4; 2 | 3 | public class KotlinFromJava { 4 | public void test() { 5 | Chapter4.cube(3); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Chapter05/src/main/java/com/packt/chapter4/OverloadsForDefaults.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class OverloadsForDefaults { 4 | 5 | public String join(String[] array) { 6 | return join(array, ""); 7 | } 8 | 9 | public String join(String[] array, String prefix) { 10 | return join(array, prefix, ""); 11 | } 12 | 13 | public String join(String[] array, String prefix, String separator) { 14 | return join(array, prefix, separator, ""); 15 | } 16 | 17 | public String join(String[] array, String prefix, String separator, String suffix) { 18 | return null; // actual impl 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter05/src/main/java/com/packt/chapter4/ThrowsFromJava.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class ThrowsFromJava { 7 | public void test() { 8 | try { 9 | Chapter4.createDirectory(new File("mobydick.txt")); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/JavaCast.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaCast { 4 | 5 | public void printStringLength(Object obj) { 6 | if (obj instanceof String) { 7 | String str = (String) obj; 8 | System.out.print(str.length()); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/JavaIf.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaIf { 4 | 5 | public boolean isZero(int x) { 6 | boolean isZero; 7 | if (x == 0) 8 | isZero = true; 9 | else 10 | isZero = false; 11 | return isZero; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/array.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val array = arrayOf(1, 2, 3) 5 | 6 | val element1 = array[0] 7 | val element2 = array[1] 8 | array[2] = 5 9 | 10 | val perfectSquares = Array(10, { k -> k * k }) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/basic_syntax.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | var name = "kotlin" 5 | name = "more kotlin" 6 | val explicitType: Double = 12.3 7 | } 8 | 9 | fun returnValueIsInferred(x: Int) = x + 1 10 | 11 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/bitwise.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | val leftShift = 1 shl 2 6 | val rightShift = 1 shr 2 7 | val unsignedRightShift = 1 ushr 2 8 | 9 | val and = 1 and 0x00001111 10 | val or = 1 and 0x00001111 11 | val xor = 1 xor 0x00001111 12 | val inv = 1.inv() 13 | } 14 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/boolean.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val x = 1 5 | val y = 2 6 | val z = 2 7 | val isTrue = x < y && x < z 8 | val alsoTrue = x == y || y == z 9 | } 10 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/char.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val chars = arrayOf('\t', '\b', '\n', '\r', '\'', '\"', '\\', '\$') 4 | 5 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/col1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun col1() { 4 | val list = listOf(1, 2, 3, 4) 5 | for (k in list) { 6 | println(k) 7 | } 8 | 9 | val set = setOf(1, 2, 3, 4) 10 | for (k in set) { 11 | println(k) 12 | } 13 | } 14 | 15 | fun colrange() { 16 | val oneToTen = 1..10 17 | for (k in oneToTen) { 18 | for (j in 1..5) { 19 | println(k * j) 20 | } 21 | } 22 | } 23 | 24 | fun stringcol() { 25 | for (char in "string") { 26 | println(char) 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/comments.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | // line comment 6 | 7 | /* 8 | A block comment 9 | can span many 10 | lines 11 | */ 12 | } 13 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/controlflowasexpression.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.util.* 5 | 6 | fun expression() { 7 | "hello".startsWith("h") 8 | } 9 | 10 | fun statement() { 11 | val a = 1 12 | } 13 | 14 | fun isZero(x: Int): Boolean { 15 | return if (x == 0) true else false 16 | } 17 | 18 | fun c1() { 19 | val date = Date() 20 | val today = if (date.year == 2016) true else false 21 | } 22 | 23 | fun t1() { 24 | fun readFile() = {} 25 | val success = try { 26 | readFile() 27 | true 28 | } catch (e: IOException) { 29 | false 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/equals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | 5 | fun eq1() { 6 | val a = File("/mobydick.doc") 7 | val b = File("/mobydick.doc") 8 | val isFalse = a === b 9 | val isTrue = a !== b 10 | } 11 | 12 | fun eq2() { 13 | val a = File("/mobydick.doc") 14 | val b = File("/mobydick.doc") 15 | val isTrue = a == b 16 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.nio.file.Files 5 | import java.nio.file.Path 6 | 7 | class File(path: String) { 8 | fun close(): Unit { 9 | } 10 | } 11 | 12 | fun openFile(): File = File("") 13 | fun readFromFile(file: File): Unit { 14 | } 15 | 16 | fun readFile(path: Path): Unit { 17 | val input = Files.newInputStream(path) 18 | try { 19 | var byte = input.read() 20 | while (byte != -1) { 21 | println(byte) 22 | byte = input.read() 23 | } 24 | } catch (e: IOException) { 25 | println("Error reading from file. Error was ${e.message}") 26 | } finally { 27 | input.close() 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/explicitWidening.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = int.toLong() 6 | 7 | val float = 12.34F 8 | val double = float.toDouble() 9 | } 10 | 11 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/forloop.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun stringIteration(string: String) { 4 | for (char in string) { 5 | println(char) 6 | } 7 | } 8 | 9 | fun arrayIndices(array: Array) { 10 | for (index in array.indices) { 11 | println("Element $index is ${array[index]}") 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/literals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = 123456L 6 | val double = 12.34 7 | val float = 12.34F 8 | val hexadecimal = 0xAB 9 | val binary = 0b01010101 10 | } 11 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/new.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | import java.math.BigDecimal 5 | import java.time.LocalDate 6 | import java.util.* 7 | 8 | fun new() { 9 | val file = File("/etc/nginx/nginx.conf") 10 | val date = BigDecimal(100) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/null.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun isNull(str: String?): Boolean = if (str == null) true else false 4 | 5 | fun foo() { 6 | var str: String? 7 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/package.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Foo 4 | 5 | fun bar(): String = "bar" -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/private.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person2 { 4 | private fun age(): Int = 21 5 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/range1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun r1() { 4 | val aToZ = "a".."z" 5 | val isTrue = "c" in aToZ 6 | 7 | val oneToNine = 1..9 8 | val isFalse = 11 in oneToNine 9 | 10 | val countingDown = 100.downTo(0) 11 | val rangeTo = 10.rangeTo(20) 12 | 13 | val oneToFifty = 1..50 14 | val oddNumbers = oneToFifty.step(2) 15 | 16 | val countingDownEvenNumbers = (2..100).step(2).reversed() 17 | 18 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/return.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import com.sun.org.apache.xml.internal.security.Init 4 | 5 | fun addTwoNumbers(a: Int, b: Int): Int { 6 | return a + b 7 | } 8 | 9 | fun largestNumber(a: Int, b: Int, c: Int): Int { 10 | fun largest(a: Int, b: Int): Int { 11 | if (a > b) return a 12 | else return b 13 | } 14 | return largest(largest(a, b), largest(b, c)) 15 | } 16 | 17 | fun printLessThanTwo() { 18 | val list = listOf(1, 2, 3, 4) 19 | list.forEach(fun(x) { 20 | if (x < 2) println(x) 21 | else return 22 | }) 23 | println("This line will still execute") 24 | } 25 | 26 | fun printUntilStop1() { 27 | val list = listOf("a", "b", "stop", "c") 28 | list.forEach stop@ { 29 | if (it == "stop") return@stop 30 | else println(it) 31 | } 32 | } 33 | 34 | fun printUntilStop2() { 35 | val list = listOf("a", "b", "stop", "c") 36 | list.forEach { 37 | if (it == "stop") return@forEach 38 | else println(it) 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/smartcasts.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun printStringLength(any: Any) { 4 | if (any is String) { 5 | println(any.length) 6 | } 7 | } 8 | 9 | 10 | fun isString(any: Any): Boolean { 11 | return if (any is String) true else false 12 | } 13 | 14 | fun isEmptyString(any: Any): Boolean { 15 | return any is String && any.length == 0 16 | } 17 | 18 | fun isNotStringOrEmpty(any: Any): Boolean { 19 | return any !is String || any.length == 0 20 | } 21 | 22 | fun length(any: Any): Int { 23 | val string = any as String 24 | return string.length 25 | } 26 | 27 | fun safeCast() { 28 | val any = "/home/users" 29 | val string: String? = any as String 30 | val file: File? = any as File 31 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/string.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val string = "string with \n new line" 4 | 5 | val rawString = """ 6 | raw string is super useful for 7 | strings that span many lines 8 | """ -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/stringconcat.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun a() { 4 | val name = "Sam" 5 | val concat = "hello " + name 6 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/stringtemplate.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun st() { 4 | val name = "Sam" 5 | val str = "hello $name. Your name has ${name.length} characters" 6 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/this.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person(name: String) { 4 | fun printMe() = println(this) 5 | } 6 | 7 | class Building(val address: String) { 8 | inner class Reception(telephone: String) { 9 | fun printMyAddress() = println(this@Building.address) 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter2/while.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun wh() { 4 | while (true) { 5 | println("This will print out for a long time!") 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.1.kt: -------------------------------------------------------------------------------- 1 | fun concat1(a: String, b: String) = a + b 2 | 3 | fun concat2(a: String, b: String): String { 4 | return a + b 5 | } 6 | 7 | fun print1(str: String): Unit { 8 | println(str) 9 | } 10 | 11 | fun print2(str: String) { 12 | println(str) 13 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.10.kt: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal 2 | 3 | class InfixExample { 4 | infix fun concat(other:String) = this.toString() + other 5 | } 6 | 7 | fun standalone() { 8 | val sum = 1 + 2 9 | 10 | val account = Account() 11 | account.add(100.00) 12 | 13 | val account2 = InfixAccount() 14 | account2 add 100.00 15 | } 16 | 17 | 18 | class Account { 19 | var balance = 0.0 20 | fun add(amount: Double): Unit { 21 | this.balance = balance + amount 22 | } 23 | } 24 | 25 | 26 | class InfixAccount { 27 | var balance = 0.0 28 | infix fun add(amount: Double): Unit { 29 | this.balance = balance + amount 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.12.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | val printHello = { println("hello") } 4 | printHello() 5 | 6 | val printMessage = { message: String -> println(message) } 7 | 8 | printMessage("hello") 9 | 10 | 11 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.13.kt: -------------------------------------------------------------------------------- 1 | fun fib(k: Int): Int = when (k) { 2 | 0 -> 1 3 | 1 -> 1 4 | else -> fib(k - 1) + fib(k - 2) 5 | } 6 | 7 | fun fact(k: Int): Int { 8 | if (k == 0) return 1 9 | else return k * fact(k - 1) 10 | } 11 | 12 | fun fact2(k: Int): Int { 13 | tailrec fun factTail(m: Int, n: Int): Int { 14 | if (m == 0) return n 15 | else return factTail(m - 1, m * n) 16 | } 17 | return factTail(k, 1) 18 | } 19 | 20 | fun main(args: Array) { 21 | for (k in 1..10) { 22 | println(fact(k)) 23 | println(fact2(k)) 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.14.vararg.kt: -------------------------------------------------------------------------------- 1 | fun multiprint(vararg strings: String): Unit { 2 | for (string in strings) 3 | println(strings) 4 | } 5 | 6 | fun multiprint2(prefix: String, vararg strings: String): Unit { 7 | println(prefix) 8 | for (string in strings) 9 | println(string) 10 | } 11 | 12 | fun multiprint3(prefix: String, vararg strings: String, suffix: String): Unit { 13 | println(prefix) 14 | for (string in strings) 15 | println(string) 16 | println(suffix) 17 | } 18 | 19 | fun varargusage() { 20 | multiprint("a", "b", "c") 21 | multiprint2("Letters", "a", "b", "c", "Finished") 22 | multiprint3("Start", "a", "b", "c", suffix = "End") 23 | } 24 | 25 | fun spreadexample() { 26 | val strings = arrayOf("a", "b", "c", "d", "e") 27 | multiprint3("Start", *strings, suffix = "End") 28 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.16.genericfuncs.kt: -------------------------------------------------------------------------------- 1 | import com.sksamuel.book.new 2 | import java.util.* 3 | 4 | fun printRepeated(t: T, k: Int): Unit { 5 | for (x in 0..k) { 6 | println(t) 7 | } 8 | } 9 | 10 | fun choose(t1: T, t2: T, t3: T): T { 11 | return when (Random().nextInt(3)) { 12 | 0 -> t1 13 | 1 -> t2 14 | else -> t3 15 | } 16 | } 17 | 18 | fun generics() { 19 | val random = choose(5, 7, 9) 20 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.17.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicInteger 2 | 3 | val counter = AtomicInteger(1) 4 | 5 | fun unpure(k: Int): Int { 6 | return counter.incrementAndGet() + k 7 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.2.kt: -------------------------------------------------------------------------------- 1 | fun square(k: Int) = k * k 2 | 3 | fun square2(k: Int): Int = k * k 4 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.20.kt: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Named 2 | import java.util.concurrent.Executors 3 | import kotlin.concurrent.thread 4 | 5 | fun getters() { 6 | val named = Named() 7 | println("My name is " + named.name) 8 | named.name = "new name" 9 | } 10 | 11 | fun sams() { 12 | val threadPool = Executors.newFixedThreadPool(4) 13 | threadPool.submit { 14 | println("I don't have a lot of work to do") 15 | } 16 | 17 | threadPool.submit(object : Runnable { 18 | override fun run() { 19 | println("I don't have a lot of work to do") 20 | } 21 | }) 22 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.22.kotlin_from_java.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("Chapter4") 2 | 3 | package com.packt.chapter4 4 | 5 | import java.io.File 6 | import java.io.IOException 7 | 8 | fun cube(n: Int): Int = n * n * n 9 | 10 | @JvmOverloads fun join(array: Array, 11 | prefix: String = "", 12 | separator: String = "", 13 | suffix: String = ""): String { 14 | return "" 15 | } 16 | 17 | @Throws(IOException::class) 18 | fun createDirectory(file: File) { 19 | if (file.exists()) 20 | throw IOException("Directory already exists") 21 | file.createNewFile() 22 | } 23 | 24 | object Erasure { 25 | fun println(array: Array): Unit {} 26 | fun println(array: Array) : Unit {} 27 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.3.kt: -------------------------------------------------------------------------------- 1 | fun hello(): String = "hello world" 2 | 3 | fun hello(name: String): String = "hello to you $name" 4 | 5 | fun invocation() { 6 | val string = "hello" 7 | val length = string.take(5) 8 | } 9 | 10 | object Square { 11 | 12 | fun printArea(width: Int, height: Int): Unit { 13 | val area = calculateArea(width, height) 14 | println("The area is $area") 15 | } 16 | 17 | fun calculateArea(width: Int, height: Int): Int { 18 | return width * height 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.5.kt: -------------------------------------------------------------------------------- 1 | fun foo(k: Int) { 2 | require(k > 10, { "k should be greater than 10" }) 3 | println(k) 4 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.6.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | 4 | val string = "a kindness of ravens" 5 | string.regionMatches(14, "Red Ravens", 4, 6, true) 6 | 7 | string.regionMatches(thisOffset = 14, other = "Red Ravens", otherOffset = 4, length = 6, ignoreCase = true) 8 | 9 | fun deleteFiles(filePattern: String, recursive: Boolean, ignoreCase: Boolean, deleteDirectories: Boolean): Unit { 10 | 11 | } 12 | 13 | deleteFiles("*.jpg", true, true, false) 14 | 15 | deleteFiles("*.jpg", recursive = true, ignoreCase = true, deleteDirectories = false) 16 | 17 | deleteFiles(filePattern = "*.jpg", deleteDirectories = false, ignoreCase = true, recursive = true) 18 | 19 | string.endsWith(suffix = "ravens", ignoreCase = true) 20 | 21 | string.endsWith(ignoreCase = true, suffix = "ravens") 22 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/4.9.kt: -------------------------------------------------------------------------------- 1 | fun positiveRoot(k: Int): Double { 2 | require(k >= 0) 3 | return Math.sqrt(k.toDouble()) 4 | } 5 | 6 | fun negativeRoot(k: Int): Double { 7 | require(k >= 0) 8 | return -Math.sqrt(k.toDouble()) 9 | } 10 | 11 | fun roots(k: Int): Array { 12 | require(k >= 0) 13 | val root = Math.sqrt(k.toDouble()) 14 | return arrayOf(root, -root) 15 | } 16 | 17 | class Roots(pos: Double, neg: Double) 18 | 19 | fun roots2(k: Int): Roots { 20 | require(k >= 0) 21 | val root = Math.sqrt(k.toDouble()) 22 | return Roots(root, -root) 23 | } 24 | 25 | fun roots3(k: Int): Pair { 26 | require(k >= 0) 27 | val root = Math.sqrt(k.toDouble()) 28 | return Pair(root, -root) 29 | } 30 | 31 | fun main() { 32 | val (pos, neg) = roots3(16) 33 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Matrix { 4 | 5 | public Matrix plus(Matrix other) { 6 | return null; 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/Named.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Named { 4 | 5 | private String name; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/infix.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | class Age(val value: Int) { 4 | infix fun max(other: Age): Age = if (value > other.value) this else other 5 | } 6 | 7 | fun foo() { 8 | val sam = Age(37) 9 | val stef = Age(36) 10 | val oldest = sam max stef 11 | } 12 | 13 | fun toVsPair() { 14 | 15 | val pair1 = Pair("london", "uk") 16 | val pair2 = "london" to "uk" 17 | 18 | val map1 = mapOf(Pair("London", "UK"), Pair("Bucharest", "Romania")) 19 | val map2 = mapOf("London" to "UK", "Bucharest" to "Romania") 20 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/matrix.kt: -------------------------------------------------------------------------------- 1 | class TwoByTwoMatrix(val a: Int, val b: Int, val c: Int, val d: Int) { 2 | operator fun plus(matrix: TwoByTwoMatrix): TwoByTwoMatrix = 3 | TwoByTwoMatrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) 4 | } 5 | 6 | fun test() { 7 | val m1 = TwoByTwoMatrix(1, 2, 3, 4) 8 | val m2 = TwoByTwoMatrix(5, 6, 7, 8) 9 | val m3 = m1 + m2 10 | } 11 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter4/singlexpfun.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | fun square(k: Int) = k * k 4 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.10.Memoization.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ConcurrentHashMap 2 | 3 | fun main(args: Array) { 4 | val memfib = memoize(::fib) 5 | val qqq = ::fib.memoized() 6 | for (k in 1..1000) { 7 | val start = System.currentTimeMillis() 8 | val result = memfib(k) 9 | val end = System.currentTimeMillis() 10 | val duration = end - start 11 | println("fib($k)=$result took $duration ms") 12 | } 13 | } 14 | 15 | val map = mutableMapOf() 16 | 17 | fun memfib(k: Int): Long { 18 | return map.getOrPut(k) { 19 | when (k) { 20 | 0 -> 1 21 | 1 -> 1 22 | else -> memfib(k - 1) + memfib(k - 2) 23 | } 24 | } 25 | } 26 | 27 | fun memoize(fn: (A) -> R): (A) -> R { 28 | val map = ConcurrentHashMap() 29 | return { a -> 30 | map.getOrPut(a) { 31 | fn(a) 32 | } 33 | } 34 | } 35 | 36 | fun Function1.memoized(): (A) -> R { 37 | val map = ConcurrentHashMap() 38 | return { a -> 39 | map.getOrPut(a) { 40 | this.invoke(a) 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.2.Closures.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | import java.util.concurrent.Executors 4 | import java.util.concurrent.atomic.AtomicInteger 5 | 6 | fun paramClosure() { 7 | 8 | class Student(val firstName: String, val lastName: String) 9 | 10 | // accesses database to load student values 11 | fun loadStudents(): List = TODO() 12 | 13 | fun students(lastName: String): List { 14 | val regex = ".*$lastName.*".toRegex() 15 | return loadStudents().filter { it.lastName.matches(regex) } 16 | } 17 | } 18 | 19 | fun localValClosure() { 20 | val counter = AtomicInteger(0) 21 | val cores = Runtime.getRuntime().availableProcessors() 22 | val threadPool = Executors.newFixedThreadPool(cores) 23 | threadPool.submit { 24 | println("I am thread number ${counter.incrementAndGet()}") 25 | } 26 | } 27 | 28 | fun mutateClosure() { 29 | var containsNegative = false 30 | val ints = listOf(0, 1, 2, 3, 4, 5) 31 | ints.forEach { 32 | if (it < 0) 33 | containsNegative = true 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.3.Anonymous.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun shortfun() { 4 | listOf(1, 2, 3).filter { it > 1 } 5 | } 6 | 7 | fun anonymousFunctions() { 8 | fun(a: String, b: String): String = a + b 9 | 10 | val ints = listOf(1, 2, 3) 11 | val evens = ints.filter(fun(k: Int) = k % 2 == 0) 12 | 13 | val evens2 = ints.filter(fun(k) = k % 2 == 0) 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.5.Receivers.kt: -------------------------------------------------------------------------------- 1 | fun foo(fn: String.() -> Boolean): Unit { 2 | "string".fn() 3 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.7.Composition.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun compose2(fn1: (A) -> B, fn2: (B) -> C): (A) -> C = { a -> 4 | val b = fn1(a) 5 | val c = fn2(b) 6 | c 7 | } 8 | 9 | fun composeExample() { 10 | 11 | val f = String::length 12 | val g = Any::hashCode 13 | val fog = compose2(f, g) 14 | println(fog("what is the hash of my length?")) 15 | 16 | } 17 | 18 | infix fun Function1.compose(fn: (R) -> R2): (P1) -> R2 = { 19 | fn(this(it)) 20 | } 21 | 22 | fun infixexample() { 23 | val f = String::length 24 | val g = Any::hashCode 25 | val fog = f compose g 26 | } 27 | 28 | operator infix fun Function1.times(fn: (R) -> R2): (P1) -> R2 = { 29 | fn(this(it)) 30 | } 31 | 32 | fun opexample() { 33 | val f = String::length 34 | val g = Any::hashCode 35 | val fog = f * g 36 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/chapter5/5.9.Currying.kt: -------------------------------------------------------------------------------- 1 | import java.util.logging.Level 2 | 3 | fun Function2.curried(): (P1) -> (P2) -> R = 4 | { p1 -> 5 | { p2 -> 6 | this(p1, p2) 7 | } 8 | } 9 | 10 | fun Function3.curried(): (P1) -> (P2) -> (P3) -> R = 11 | { p1 -> 12 | { p2 -> 13 | { p3 -> 14 | this(p1, p2, p3) 15 | } 16 | } 17 | } 18 | 19 | fun logger(level: Level, appender: Appendable, msg: String): Nothing = TODO() 20 | 21 | fun curryExample() { 22 | val logger: (Level) -> (Appendable) -> (String) -> Unit = ::logger.curried() 23 | val logger2: (Appendable) -> (String) -> Unit = logger(Level.SEVERE) 24 | val logger3: (String) -> Unit = logger2(System.out) 25 | logger3("my message") 26 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/myproject/constants/import1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject.constants 2 | 3 | val PI = 3.142 4 | val E = 2.178 5 | 6 | class Foo -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/myproject/import2.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject 2 | 3 | import com.packt.myproject.Foo 4 | import com.packt.otherproject.Foo as Foo2 5 | 6 | fun doubleFoo() { 7 | val foo1 = Foo() 8 | val foo2 = Foo2() 9 | } -------------------------------------------------------------------------------- /Chapter05/src/main/kotlin/com/packt/otherproject/Foo.kt: -------------------------------------------------------------------------------- 1 | package com.packt.otherproject 2 | 3 | class Foo -------------------------------------------------------------------------------- /Chapter06/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter06/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'properties' 2 | 3 | -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/DelayedInit.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | 4 | class Container { 5 | lateinit var delayedInitProperty: DelayedInstance 6 | fun initProperty(instance: DelayedInstance): Unit { 7 | this.delayedInitProperty = instance 8 | } 9 | } 10 | 11 | class DelayedInstance (val number:Int) -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Delegate.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import org.joda.time.DateTime 4 | import kotlin.reflect.KProperty 5 | 6 | interface WithId { 7 | val id: String 8 | } 9 | 10 | data class WithIdImpl(override val id: String) : WithId 11 | 12 | class Record(id: String) : WithId by Record.identifier(id) { 13 | companion object Record { 14 | fun identifier(identifier: String) = WithIdImpl(identifier) 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/LazyProperty.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | class WithLazyProperty { 4 | val foo: Int by lazy (){ 5 | println("Initializing foo") 6 | 2 7 | } 8 | } 9 | 10 | class WithLazyPropertyWithLocking{ 11 | val lockingField = Any() 12 | 13 | val foo: Int by lazy(lockingField, { 14 | println("Initializing foo"); 15 | 2 16 | }) 17 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Lookup.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import java.util.* 4 | 5 | class Lookup { 6 | private var _keywords: HashSet? = null 7 | 8 | val keywords: Iterable 9 | get() { 10 | if (_keywords == null) { 11 | _keywords = HashSet() 12 | } 13 | return _keywords ?: throw RuntimeException("Invalid keywords") 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Measure.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import kotlin.reflect.KProperty 4 | 5 | class TimestampValueDelegate { 6 | private var timestamp = 0L 7 | operator fun getValue(ref: Any?, property: KProperty<*>): Long { 8 | return timestamp; 9 | } 10 | 11 | operator fun setValue(ref: Any?, property: KProperty<*>, value: Long) { 12 | timestamp = value 13 | } 14 | } 15 | 16 | class Measure { 17 | var writeTimestamp: Long by TimestampValueDelegate() 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/NonNullProp.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import kotlin.properties.Delegates 4 | 5 | 6 | class NonNullProp { 7 | var value: String by Delegates.notNull() 8 | 9 | var value2:ForProp by Delegates.notNull() 10 | } 11 | 12 | data class ForProp(val someField:String) -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Player.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | class Player(val map: Map) { 4 | val name: String by map 5 | val age: Int by map 6 | val height: Double by map 7 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/PropsByMap.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import kotlin.reflect.KProperty 4 | 5 | class MapDelegate { 6 | private val map = mutableMapOf() 7 | operator fun getValue(ref: Any?, property: KProperty<*>): T { 8 | return map[property.name] as T 9 | } 10 | 11 | operator fun setValue(ref: Any?, property: KProperty<*>, value: T?) { 12 | map.put(property.name, value) 13 | } 14 | } 15 | 16 | data class SomeData(val char: Char) 17 | 18 | class PropsByMap() { 19 | private val mapDelegate = MapDelegate() 20 | var p1: Int by mapDelegate 21 | 22 | val p2: SomeData by mapDelegate 23 | 24 | init { 25 | mapDelegate.setValue(this, PropsByMap::p2, SomeData('K')) 26 | mapDelegate.setValue(this, PropsByMap::p1, 0) 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Shape.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | interface Shape { 4 | val Area: Double 5 | get; 6 | } 7 | 8 | class Rectangle(val width: Double, val height: Double) : Shape { 9 | override val Area: Double 10 | get() = width * height 11 | 12 | val isSquare: Boolean 13 | get() = width == height 14 | 15 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Student.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | class Student(var name: String, var age: Int) { 4 | /* 5 | public var Name = "" 6 | set(value) { 7 | field = value 8 | } 9 | 10 | public var Age = 20 11 | set(value) { 12 | field = value 13 | } 14 | 15 | init { 16 | Name = name 17 | Age = age 18 | }*/ 19 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/Trivial.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import kotlin.properties.ReadOnlyProperty 4 | import kotlin.reflect.KProperty 5 | 6 | data class TrivialProperty(private val const: Int) : ReadOnlyProperty { 7 | override fun getValue(thisRef: Trivial, property: KProperty<*>): Int { 8 | return const; 9 | } 10 | } 11 | 12 | class Trivial { 13 | val flag: Int by TrivialProperty(999) 14 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/WithInheritance.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | open class WithInheritance { 4 | open var isAvailable: Boolean = false 5 | get() = field 6 | protected set(value) { 7 | field = value 8 | } 9 | } 10 | 11 | class WithInheritanceDerived(isAvailable: Boolean) : WithInheritance() { 12 | override var isAvailable: Boolean = isAvailable 13 | get() { 14 | //do something before returning the value 15 | return super.isAvailable 16 | } 17 | set(value) { 18 | //do something else before setting the value 19 | println("WithInhertianceDerived.isAvailable") 20 | field = value 21 | } 22 | 23 | fun doSomething() { 24 | isAvailable = false 25 | } 26 | } -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/WithObservableProp.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import kotlin.properties.Delegates 4 | 5 | 6 | class WithObservableProp { 7 | var value: Int by Delegates.observable(0) { p, oldNew, newVal -> onValueChanged() } 8 | 9 | private fun onValueChanged() { 10 | println("value has changed:$value") 11 | } 12 | } 13 | 14 | 15 | class OnlyPositiveValues { 16 | var value: Int by Delegates.vetoable(0) { p, oldNew, newVal -> newVal >= 0 } 17 | } 18 | -------------------------------------------------------------------------------- /Chapter06/src/main/kotlin/com/programming/kotlin/chapter06/WithPrivateSetter.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter06 2 | 3 | import java.util.* 4 | 5 | class WithPrivateSetter(property: Int) { 6 | var SomeProperty: Int = 0 7 | private set(value) { 8 | field = value 9 | } 10 | 11 | init { 12 | SomeProperty = property 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter07/src/main/java/KotlinFromJava.java: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Chapter4; 2 | 3 | public class KotlinFromJava { 4 | public void test() { 5 | Chapter4.cube(3); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Chapter07/src/main/java/com/packt/chapter4/OverloadsForDefaults.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class OverloadsForDefaults { 4 | 5 | public String join(String[] array) { 6 | return join(array, ""); 7 | } 8 | 9 | public String join(String[] array, String prefix) { 10 | return join(array, prefix, ""); 11 | } 12 | 13 | public String join(String[] array, String prefix, String separator) { 14 | return join(array, prefix, separator, ""); 15 | } 16 | 17 | public String join(String[] array, String prefix, String separator, String suffix) { 18 | return null; // actual impl 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter07/src/main/java/com/packt/chapter4/ThrowsFromJava.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class ThrowsFromJava { 7 | public void test() { 8 | try { 9 | Chapter4.createDirectory(new File("mobydick.txt")); 10 | } catch (IOException e) { 11 | e.printStackTrace(); 12 | } 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter07/src/main/java/com/packt/chapter7/StaticFuncs.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7; 2 | 3 | public class StaticFuncs { 4 | public StaticFuncs() { 5 | HasStaticFuncs.INSTANCE.foo(); 6 | HasStaticFuncs.foo(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Chapter07/src/main/java/com/packt/chapter7/ThrowsExample.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7; 2 | 3 | import java.io.FileNotFoundException; 4 | 5 | public class ThrowsExample { 6 | public void throwsExample() throws FileNotFoundException { 7 | boolean exists = new File("somefile.txt").exists(); 8 | System.out.println("File exists"); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/JavaCast.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaCast { 4 | 5 | public void printStringLength(Object obj) { 6 | if (obj instanceof String) { 7 | String str = (String) obj; 8 | System.out.print(str.length()); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/JavaIf.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2; 2 | 3 | public class JavaIf { 4 | 5 | public boolean isZero(int x) { 6 | boolean isZero; 7 | if (x == 0) 8 | isZero = true; 9 | else 10 | isZero = false; 11 | return isZero; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/array.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val array = arrayOf(1, 2, 3) 5 | 6 | val element1 = array[0] 7 | val element2 = array[1] 8 | array[2] = 5 9 | 10 | val perfectSquares = Array(10, { k -> k * k }) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/basic_syntax.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | var name = "kotlin" 5 | name = "more kotlin" 6 | val explicitType: Double = 12.3 7 | } 8 | 9 | fun returnValueIsInferred(x: Int) = x + 1 10 | 11 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/bitwise.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | val leftShift = 1 shl 2 6 | val rightShift = 1 shr 2 7 | val unsignedRightShift = 1 ushr 2 8 | 9 | val and = 1 and 0x00001111 10 | val or = 1 and 0x00001111 11 | val xor = 1 xor 0x00001111 12 | val inv = 1.inv() 13 | } 14 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/boolean.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val x = 1 5 | val y = 2 6 | val z = 2 7 | val isTrue = x < y && x < z 8 | val alsoTrue = x == y || y == z 9 | } 10 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/char.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val chars = arrayOf('\t', '\b', '\n', '\r', '\'', '\"', '\\', '\$') 4 | 5 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/col1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun col1() { 4 | val list = listOf(1, 2, 3, 4) 5 | for (k in list) { 6 | println(k) 7 | } 8 | 9 | val set = setOf(1, 2, 3, 4) 10 | for (k in set) { 11 | println(k) 12 | } 13 | } 14 | 15 | fun colrange() { 16 | val oneToTen = 1..10 17 | for (k in oneToTen) { 18 | for (j in 1..5) { 19 | println(k * j) 20 | } 21 | } 22 | } 23 | 24 | fun stringcol() { 25 | for (char in "string") { 26 | println(char) 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/comments.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | 5 | // line comment 6 | 7 | /* 8 | A block comment 9 | can span many 10 | lines 11 | */ 12 | } 13 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/controlflowasexpression.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.util.* 5 | 6 | fun expression() { 7 | "hello".startsWith("h") 8 | } 9 | 10 | fun statement() { 11 | val a = 1 12 | } 13 | 14 | fun isZero(x: Int): Boolean { 15 | return if (x == 0) true else false 16 | } 17 | 18 | fun c1() { 19 | val date = Date() 20 | val today = if (date.year == 2016) true else false 21 | } 22 | 23 | fun t1() { 24 | fun readFile() = {} 25 | val success = try { 26 | readFile() 27 | true 28 | } catch (e: IOException) { 29 | false 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/equals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | 5 | fun eq1() { 6 | val a = File("/mobydick.doc") 7 | val b = File("/mobydick.doc") 8 | val isFalse = a === b 9 | val isTrue = a !== b 10 | } 11 | 12 | fun eq2() { 13 | val a = File("/mobydick.doc") 14 | val b = File("/mobydick.doc") 15 | val isTrue = a == b 16 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.IOException 4 | import java.nio.file.Files 5 | import java.nio.file.Path 6 | 7 | class File(path: String) { 8 | fun close(): Unit { 9 | } 10 | } 11 | 12 | fun openFile(): File = File("") 13 | fun readFromFile(file: File): Unit { 14 | } 15 | 16 | fun readFile(path: Path): Unit { 17 | val input = Files.newInputStream(path) 18 | try { 19 | var byte = input.read() 20 | while (byte != -1) { 21 | println(byte) 22 | byte = input.read() 23 | } 24 | } catch (e: IOException) { 25 | println("Error reading from file. Error was ${e.message}") 26 | } finally { 27 | input.close() 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/explicitWidening.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = int.toLong() 6 | 7 | val float = 12.34F 8 | val double = float.toDouble() 9 | } 10 | 11 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/forloop.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun stringIteration(string: String) { 4 | for (char in string) { 5 | println(char) 6 | } 7 | } 8 | 9 | fun arrayIndices(array: Array) { 10 | for (index in array.indices) { 11 | println("Element $index is ${array[index]}") 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/literals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun main(args: Array) { 4 | val int = 123 5 | val long = 123456L 6 | val double = 12.34 7 | val float = 12.34F 8 | val hexadecimal = 0xAB 9 | val binary = 0b01010101 10 | } 11 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/new.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import java.io.File 4 | import java.math.BigDecimal 5 | import java.time.LocalDate 6 | import java.util.* 7 | 8 | fun new() { 9 | val file = File("/etc/nginx/nginx.conf") 10 | val date = BigDecimal(100) 11 | } 12 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/null.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun isNull(str: String?): Boolean = if (str == null) true else false 4 | 5 | fun foo() { 6 | var str: String? 7 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/package.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Foo 4 | 5 | fun bar(): String = "bar" -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/private.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person2 { 4 | private fun age(): Int = 21 5 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/range1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun r1() { 4 | val aToZ = "a".."z" 5 | val isTrue = "c" in aToZ 6 | 7 | val oneToNine = 1..9 8 | val isFalse = 11 in oneToNine 9 | 10 | val countingDown = 100.downTo(0) 11 | val rangeTo = 10.rangeTo(20) 12 | 13 | val oneToFifty = 1..50 14 | val oddNumbers = oneToFifty.step(2) 15 | 16 | val countingDownEvenNumbers = (2..100).step(2).reversed() 17 | 18 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/return.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | import com.sun.org.apache.xml.internal.security.Init 4 | 5 | fun addTwoNumbers(a: Int, b: Int): Int { 6 | return a + b 7 | } 8 | 9 | fun largestNumber(a: Int, b: Int, c: Int): Int { 10 | fun largest(a: Int, b: Int): Int { 11 | if (a > b) return a 12 | else return b 13 | } 14 | return largest(largest(a, b), largest(b, c)) 15 | } 16 | 17 | fun printLessThanTwo() { 18 | val list = listOf(1, 2, 3, 4) 19 | list.forEach(fun(x) { 20 | if (x < 2) println(x) 21 | else return 22 | }) 23 | println("This line will still execute") 24 | } 25 | 26 | fun printUntilStop1() { 27 | val list = listOf("a", "b", "stop", "c") 28 | list.forEach stop@ { 29 | if (it == "stop") return@stop 30 | else println(it) 31 | } 32 | } 33 | 34 | fun printUntilStop2() { 35 | val list = listOf("a", "b", "stop", "c") 36 | list.forEach { 37 | if (it == "stop") return@forEach 38 | else println(it) 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/smartcasts.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun printStringLength(any: Any) { 4 | if (any is String) { 5 | println(any.length) 6 | } 7 | } 8 | 9 | 10 | fun isString(any: Any): Boolean { 11 | return if (any is String) true else false 12 | } 13 | 14 | fun isEmptyString(any: Any): Boolean { 15 | return any is String && any.length == 0 16 | } 17 | 18 | fun isNotStringOrEmpty(any: Any): Boolean { 19 | return any !is String || any.length == 0 20 | } 21 | 22 | fun length(any: Any): Int { 23 | val string = any as String 24 | return string.length 25 | } 26 | 27 | fun safeCast() { 28 | val any = "/home/users" 29 | val string: String? = any as String 30 | val file: File? = any as File 31 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/string.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | val string = "string with \n new line" 4 | 5 | val rawString = """ 6 | raw string is super useful for 7 | strings that span many lines 8 | """ -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/stringconcat.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun a() { 4 | val name = "Sam" 5 | val concat = "hello " + name 6 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/stringtemplate.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun st() { 4 | val name = "Sam" 5 | val str = "hello $name. Your name has ${name.length} characters" 6 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/this.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | class Person(name: String) { 4 | fun printMe() = println(this) 5 | } 6 | 7 | class Building(val address: String) { 8 | inner class Reception(telephone: String) { 9 | fun printMyAddress() = println(this@Building.address) 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter2/while.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter2 2 | 3 | fun wh() { 4 | while (true) { 5 | println("This will print out for a long time!") 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.1.kt: -------------------------------------------------------------------------------- 1 | fun concat1(a: String, b: String) = a + b 2 | 3 | fun concat2(a: String, b: String): String { 4 | return a + b 5 | } 6 | 7 | fun print1(str: String): Unit { 8 | println(str) 9 | } 10 | 11 | fun print2(str: String) { 12 | println(str) 13 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.10.kt: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal 2 | 3 | class InfixExample { 4 | infix fun concat(other:String) = this.toString() + other 5 | } 6 | 7 | fun standalone() { 8 | val sum = 1 + 2 9 | 10 | val account = Account() 11 | account.add(100.00) 12 | 13 | val account2 = InfixAccount() 14 | account2 add 100.00 15 | } 16 | 17 | 18 | class Account { 19 | var balance = 0.0 20 | fun add(amount: Double): Unit { 21 | this.balance = balance + amount 22 | } 23 | } 24 | 25 | 26 | class InfixAccount { 27 | var balance = 0.0 28 | infix fun add(amount: Double): Unit { 29 | this.balance = balance + amount 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.12.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | val printHello = { println("hello") } 4 | printHello() 5 | 6 | val printMessage = { message: String -> println(message) } 7 | 8 | printMessage("hello") 9 | 10 | 11 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.13.kt: -------------------------------------------------------------------------------- 1 | fun fib(k: Int): Int = when (k) { 2 | 0 -> 1 3 | 1 -> 1 4 | else -> fib(k - 1) + fib(k - 2) 5 | } 6 | 7 | fun fact(k: Int): Int { 8 | if (k == 0) return 1 9 | else return k * fact(k - 1) 10 | } 11 | 12 | fun fact2(k: Int): Int { 13 | tailrec fun factTail(m: Int, n: Int): Int { 14 | if (m == 0) return n 15 | else return factTail(m - 1, m * n) 16 | } 17 | return factTail(k, 1) 18 | } 19 | 20 | fun main(args: Array) { 21 | for (k in 1..10) { 22 | println(fact(k)) 23 | println(fact2(k)) 24 | } 25 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.14.vararg.kt: -------------------------------------------------------------------------------- 1 | fun multiprint(vararg strings: String): Unit { 2 | for (string in strings) 3 | println(strings) 4 | } 5 | 6 | fun multiprint2(prefix: String, vararg strings: String): Unit { 7 | println(prefix) 8 | for (string in strings) 9 | println(string) 10 | } 11 | 12 | fun multiprint3(prefix: String, vararg strings: String, suffix: String): Unit { 13 | println(prefix) 14 | for (string in strings) 15 | println(string) 16 | println(suffix) 17 | } 18 | 19 | fun varargusage() { 20 | multiprint("a", "b", "c") 21 | multiprint2("Letters", "a", "b", "c", "Finished") 22 | multiprint3("Start", "a", "b", "c", suffix = "End") 23 | } 24 | 25 | fun spreadexample() { 26 | val strings = arrayOf("a", "b", "c", "d", "e") 27 | multiprint3("Start", *strings, suffix = "End") 28 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.16.genericfuncs.kt: -------------------------------------------------------------------------------- 1 | import java.util.* 2 | 3 | fun printRepeated(t: T, k: Int): Unit { 4 | for (x in 0..k) { 5 | println(t) 6 | } 7 | } 8 | 9 | fun choose(t1: T, t2: T, t3: T): T { 10 | return when (Random().nextInt(3)) { 11 | 0 -> t1 12 | 1 -> t2 13 | else -> t3 14 | } 15 | } 16 | 17 | fun generics() { 18 | val random = choose(5, 7, 9) 19 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.17.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.atomic.AtomicInteger 2 | 3 | val counter = AtomicInteger(1) 4 | 5 | fun unpure(k: Int): Int { 6 | return counter.incrementAndGet() + k 7 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.2.kt: -------------------------------------------------------------------------------- 1 | fun square(k: Int) = k * k 2 | 3 | fun square2(k: Int): Int = k * k 4 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.20.kt: -------------------------------------------------------------------------------- 1 | import com.packt.chapter4.Named 2 | import java.util.concurrent.Executors 3 | import kotlin.concurrent.thread 4 | 5 | fun getters() { 6 | val named = Named() 7 | println("My name is " + named.name) 8 | named.name = "new name" 9 | } 10 | 11 | fun sams() { 12 | val threadPool = Executors.newFixedThreadPool(4) 13 | threadPool.submit { 14 | println("I don't have a lot of work to do") 15 | } 16 | 17 | threadPool.submit(object : Runnable { 18 | override fun run() { 19 | println("I don't have a lot of work to do") 20 | } 21 | }) 22 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.22.kotlin_from_java.kt: -------------------------------------------------------------------------------- 1 | @file:JvmName("Chapter4") 2 | 3 | package com.packt.chapter4 4 | 5 | import java.io.File 6 | import java.io.IOException 7 | 8 | fun cube(n: Int): Int = n * n * n 9 | 10 | @JvmOverloads fun join(array: Array, 11 | prefix: String = "", 12 | separator: String = "", 13 | suffix: String = ""): String { 14 | return "" 15 | } 16 | 17 | @Throws(IOException::class) 18 | fun createDirectory(file: File) { 19 | if (file.exists()) 20 | throw IOException("Directory already exists") 21 | file.createNewFile() 22 | } 23 | 24 | object Erasure { 25 | fun println(array: Array): Unit {} 26 | fun println(array: Array) : Unit {} 27 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.3.kt: -------------------------------------------------------------------------------- 1 | fun hello(): String = "hello world" 2 | 3 | fun hello(name: String): String = "hello to you $name" 4 | 5 | fun invocation() { 6 | val string = "hello" 7 | val length = string.take(5) 8 | } 9 | 10 | object Square { 11 | 12 | fun printArea(width: Int, height: Int): Unit { 13 | val area = calculateArea(width, height) 14 | println("The area is $area") 15 | } 16 | 17 | fun calculateArea(width: Int, height: Int): Int { 18 | return width * height 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.5.kt: -------------------------------------------------------------------------------- 1 | fun foo(k: Int) { 2 | require(k > 10, { "k should be greater than 10" }) 3 | println(k) 4 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.6.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | 3 | 4 | val string = "a kindness of ravens" 5 | string.regionMatches(14, "Red Ravens", 4, 6, true) 6 | 7 | string.regionMatches(thisOffset = 14, other = "Red Ravens", otherOffset = 4, length = 6, ignoreCase = true) 8 | 9 | fun deleteFiles(filePattern: String, recursive: Boolean, ignoreCase: Boolean, deleteDirectories: Boolean): Unit { 10 | 11 | } 12 | 13 | deleteFiles("*.jpg", true, true, false) 14 | 15 | deleteFiles("*.jpg", recursive = true, ignoreCase = true, deleteDirectories = false) 16 | 17 | deleteFiles(filePattern = "*.jpg", deleteDirectories = false, ignoreCase = true, recursive = true) 18 | 19 | string.endsWith(suffix = "ravens", ignoreCase = true) 20 | 21 | string.endsWith(ignoreCase = true, suffix = "ravens") 22 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/4.9.kt: -------------------------------------------------------------------------------- 1 | fun positiveRoot(k: Int): Double { 2 | require(k >= 0) 3 | return Math.sqrt(k.toDouble()) 4 | } 5 | 6 | fun negativeRoot(k: Int): Double { 7 | require(k >= 0) 8 | return -Math.sqrt(k.toDouble()) 9 | } 10 | 11 | fun roots(k: Int): Array { 12 | require(k >= 0) 13 | val root = Math.sqrt(k.toDouble()) 14 | return arrayOf(root, -root) 15 | } 16 | 17 | class Roots(pos: Double, neg: Double) 18 | 19 | fun roots2(k: Int): Roots { 20 | require(k >= 0) 21 | val root = Math.sqrt(k.toDouble()) 22 | return Roots(root, -root) 23 | } 24 | 25 | fun roots3(k: Int): Pair { 26 | require(k >= 0) 27 | val root = Math.sqrt(k.toDouble()) 28 | return Pair(root, -root) 29 | } 30 | 31 | fun main() { 32 | val (pos, neg) = roots3(16) 33 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/Matrix.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Matrix { 4 | 5 | public Matrix plus(Matrix other) { 6 | return null; 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/Named.java: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4; 2 | 3 | public class Named { 4 | 5 | private String name; 6 | 7 | public String getName() { 8 | return name; 9 | } 10 | 11 | public void setName(String name) { 12 | this.name = name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/infix.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | class Age(val value: Int) { 4 | infix fun max(other: Age): Age = if (value > other.value) this else other 5 | } 6 | 7 | fun foo() { 8 | val sam = Age(37) 9 | val stef = Age(36) 10 | val oldest = sam max stef 11 | } 12 | 13 | fun toVsPair() { 14 | 15 | val pair1 = Pair("london", "uk") 16 | val pair2 = "london" to "uk" 17 | 18 | val map1 = mapOf(Pair("London", "UK"), Pair("Bucharest", "Romania")) 19 | val map2 = mapOf("London" to "UK", "Bucharest" to "Romania") 20 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/matrix.kt: -------------------------------------------------------------------------------- 1 | class TwoByTwoMatrix(val a: Int, val b: Int, val c: Int, val d: Int) { 2 | operator fun plus(matrix: TwoByTwoMatrix): TwoByTwoMatrix = 3 | TwoByTwoMatrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) 4 | } 5 | 6 | fun test() { 7 | val m1 = TwoByTwoMatrix(1, 2, 3, 4) 8 | val m2 = TwoByTwoMatrix(5, 6, 7, 8) 9 | val m3 = m1 + m2 10 | } 11 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter4/singlexpfun.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter4 2 | 3 | fun square(k: Int) = k * k 4 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.10.Memoization.kt: -------------------------------------------------------------------------------- 1 | import java.util.concurrent.ConcurrentHashMap 2 | 3 | fun main(args: Array) { 4 | val memfib = memoize(::fib) 5 | val qqq = ::fib.memoized() 6 | for (k in 1..1000) { 7 | val start = System.currentTimeMillis() 8 | val result = memfib(k) 9 | val end = System.currentTimeMillis() 10 | val duration = end - start 11 | println("fib($k)=$result took $duration ms") 12 | } 13 | } 14 | 15 | val map = mutableMapOf() 16 | 17 | fun memfib(k: Int): Long { 18 | return map.getOrPut(k) { 19 | when (k) { 20 | 0 -> 1 21 | 1 -> 1 22 | else -> memfib(k - 1) + memfib(k - 2) 23 | } 24 | } 25 | } 26 | 27 | fun memoize(fn: (A) -> R): (A) -> R { 28 | val map = ConcurrentHashMap() 29 | return { a -> 30 | map.getOrPut(a) { 31 | fn(a) 32 | } 33 | } 34 | } 35 | 36 | fun Function1.memoized(): (A) -> R { 37 | val map = ConcurrentHashMap() 38 | return { a -> 39 | map.getOrPut(a) { 40 | this.invoke(a) 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.2.Closures.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | import java.util.concurrent.Executors 4 | import java.util.concurrent.atomic.AtomicInteger 5 | 6 | fun paramClosure() { 7 | 8 | class Student(val firstName: String, val lastName: String) 9 | 10 | // accesses database to load student values 11 | fun loadStudents(): List = TODO() 12 | 13 | fun students(lastName: String): List { 14 | val regex = ".*$lastName.*".toRegex() 15 | return loadStudents().filter { it.lastName.matches(regex) } 16 | } 17 | } 18 | 19 | fun localValClosure() { 20 | val counter = AtomicInteger(0) 21 | val cores = Runtime.getRuntime().availableProcessors() 22 | val threadPool = Executors.newFixedThreadPool(cores) 23 | threadPool.submit { 24 | println("I am thread number ${counter.incrementAndGet()}") 25 | } 26 | } 27 | 28 | fun mutateClosure() { 29 | var containsNegative = false 30 | val ints = listOf(0, 1, 2, 3, 4, 5) 31 | ints.forEach { 32 | if (it < 0) 33 | containsNegative = true 34 | } 35 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.3.Anonymous.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun shortfun() { 4 | listOf(1, 2, 3).filter { it > 1 } 5 | } 6 | 7 | fun anonymousFunctions() { 8 | fun(a: String, b: String): String = a + b 9 | 10 | val ints = listOf(1, 2, 3) 11 | val evens = ints.filter(fun(k: Int) = k % 2 == 0) 12 | 13 | val evens2 = ints.filter(fun(k) = k % 2 == 0) 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.5.Receivers.kt: -------------------------------------------------------------------------------- 1 | fun foo(fn: String.() -> Boolean): Unit { 2 | "string".fn() 3 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.7.Composition.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter5 2 | 3 | fun compose2(fn1: (A) -> B, fn2: (B) -> C): (A) -> C = { a -> 4 | val b = fn1(a) 5 | val c = fn2(b) 6 | c 7 | } 8 | 9 | fun composeExample() { 10 | 11 | val f = String::length 12 | val g = Any::hashCode 13 | val fog = compose2(f, g) 14 | println(fog("what is the hash of my length?")) 15 | 16 | } 17 | 18 | infix fun Function1.compose(fn: (R) -> R2): (P1) -> R2 = { 19 | fn(this(it)) 20 | } 21 | 22 | fun infixexample() { 23 | val f = String::length 24 | val g = Any::hashCode 25 | val fog = f compose g 26 | } 27 | 28 | operator infix fun Function1.times(fn: (R) -> R2): (P1) -> R2 = { 29 | fn(this(it)) 30 | } 31 | 32 | fun opexample() { 33 | val f = String::length 34 | val g = Any::hashCode 35 | val fog = f * g 36 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter5/5.9.Currying.kt: -------------------------------------------------------------------------------- 1 | import java.util.logging.Level 2 | 3 | fun Function2.curried(): (P1) -> (P2) -> R = 4 | { p1 -> 5 | { p2 -> 6 | this(p1, p2) 7 | } 8 | } 9 | 10 | fun Function3.curried(): (P1) -> (P2) -> (P3) -> R = 11 | { p1 -> 12 | { p2 -> 13 | { p3 -> 14 | this(p1, p2, p3) 15 | } 16 | } 17 | } 18 | 19 | fun logger(level: Level, appender: Appendable, msg: String): Nothing = TODO() 20 | 21 | fun curryExample() { 22 | val logger: (Level) -> (Appendable) -> (String) -> Unit = ::logger.curried() 23 | val logger2: (Appendable) -> (String) -> Unit = logger(Level.SEVERE) 24 | val logger3: (String) -> Unit = logger2(System.out) 25 | logger3("my message") 26 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.10.Instantiation.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | import java.nio.file.Files 4 | import java.nio.file.Paths 5 | import java.util.* 6 | import kotlin.reflect.KClass 7 | import kotlin.reflect.createInstance 8 | 9 | class PositiveInteger(value: Int = 0) 10 | 11 | fun createInteger(kclass: KClass): PositiveInteger { 12 | return kclass.createInstance() 13 | } 14 | 15 | interface Ingester { 16 | fun ingest(): Unit 17 | } 18 | 19 | fun ingesters() { 20 | 21 | val props = Properties() 22 | props.load(Files.newInputStream(Paths.get("/some/path/to/config"))) 23 | 24 | val classNames = (props.getProperty("ingesters") ?: "").split(',') 25 | 26 | val ingesters = classNames.map { 27 | Class.forName(it).kotlin.createInstance() as Ingester 28 | } 29 | 30 | ingesters.forEach { it.ingest() } 31 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.12.Objects.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | import kotlin.reflect.companionObject 4 | import kotlin.reflect.companionObjectInstance 5 | 6 | class Aircraft(name: String, manufacturer: String, capacity: Int) { 7 | companion object { 8 | fun boeing(name: String, capacity: Int) = Aircraft(name, "Boeing", capacity) 9 | } 10 | } 11 | 12 | fun companionObjectKClass() { 13 | val kclass = Aircraft::class 14 | val companionKClass = kclass.companionObject 15 | } 16 | 17 | fun companionObject() { 18 | val kclass = Aircraft::class 19 | val companion = kclass.companionObjectInstance as Aircraft.Companion 20 | companion.boeing("747", 999) 21 | } 22 | 23 | class Pizza(name: String) 24 | 25 | object PizzaOven { 26 | fun cook(name: String): Pizza = Pizza(name) 27 | } 28 | 29 | fun objectKClass() { 30 | val kclass = PizzaOven::class 31 | val oven = kclass.objectInstance as PizzaOven 32 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.13.UsefulKClassProperties.kt: -------------------------------------------------------------------------------- 1 | import java.io.Closeable 2 | import java.io.Serializable 3 | import kotlin.reflect.allSuperclasses 4 | import kotlin.reflect.superclasses 5 | 6 | class Sandwich() 7 | 8 | class ManyParents : Serializable, Closeable, java.lang.AutoCloseable { 9 | override fun close() { 10 | } 11 | } 12 | 13 | fun main(args: Array) { 14 | 15 | val types = Sandwich::class.typeParameters 16 | types.forEach { 17 | println("Type ${it.name} has upper bound ${it.upperBounds}") 18 | } 19 | 20 | val superclasses = ManyParents::class.superclasses 21 | superclasses.forEach { 22 | println(it) 23 | } 24 | 25 | val allSuperclasses = ManyParents::class.allSuperclasses 26 | allSuperclasses.forEach { 27 | println(it) 28 | } 29 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.16.1.jvmnameannotation.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | @JvmName("filterStrings") 4 | fun filter(list: List): Unit { 5 | } 6 | 7 | @JvmName("filterInts") 8 | fun filter(list: List): Unit { 9 | } 10 | 11 | fun test() { 12 | println(filter(listOf(1, 2, 3))) 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.16.2.JvmStatic.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | object HasStaticFuncs { 4 | @JvmStatic 5 | fun foo(): Unit { 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.16.3.Throws.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | import java.io.FileNotFoundException 4 | import java.nio.file.Paths 5 | import kotlin.jvm.Throws 6 | 7 | class File(val path: String) { 8 | @Throws(FileNotFoundException::class) 9 | fun exists(): Boolean { 10 | if (!Paths.get(path).toFile().exists()) 11 | throw FileNotFoundException("$path does not exist") 12 | return true 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.16.4.JvmOverloads.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | class SomeClass() { 4 | @JvmOverloads 5 | fun foo(name: String = "Harry", location: String = "Cardiff"): Unit { 6 | } 7 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.5.ElvisOperator.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | fun javaStyle(address: Address) { 4 | var postcode: String? = null 5 | if (address == null) { 6 | postcode = "No Postcode" 7 | } else { 8 | if (address.postcode == null) { 9 | postcode = "No Postcode" 10 | } else { 11 | postcode = address.postcode 12 | } 13 | } 14 | } 15 | 16 | fun exampleElvis() { 17 | val nullableName: String? = "william" 18 | val name: String = nullableName ?: "default_name" 19 | 20 | val nullableAddress: Address? = null 21 | val postcode: String = nullableAddress?.postcode ?: "default_postcode" 22 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.6.Safecasts.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | fun safeCast() { 4 | val location: Any = "London" 5 | 6 | val safeString: String? = location as? String 7 | val safeInt: Int? = location as? Int 8 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.7.optionals.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | import java.util.* 4 | 5 | val optionalName: Optional = Optional.of("william") 6 | 7 | val empty: Optional = Optional.empty() 8 | 9 | fun lookupAddress(postcode: String): Optional = TODO() 10 | fun lookupHousePrice(address: String): Optional = TODO() 11 | 12 | fun orElse() { 13 | val address = lookupAddress("AB1 1BC").orElse("1600 Pennsylvania Avenue") 14 | } 15 | 16 | fun qe() { 17 | val price = lookupAddress("AB1 1BC").flatMap(::lookupHousePrice).orElse(0) 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/chapter7/7.9.KClass.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter7 2 | 3 | import kotlin.reflect.KClass 4 | 5 | fun gettingAKClass() { 6 | val name = "George" 7 | val kclass: KClass = name::class 8 | val kclass2: KClass = String::class 9 | val kclass3 = Class.forName("com.packt.MyType").kotlin 10 | } 11 | 12 | fun oneKClassPerType() { 13 | val kclass1: KClass = "harry"::class 14 | val kclass2: KClass = "victoria"::class 15 | val kclass3: KClass = String::class 16 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/myproject/constants/import1.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject.constants 2 | 3 | val PI = 3.142 4 | val E = 2.178 5 | 6 | class Foo -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/myproject/import2.kt: -------------------------------------------------------------------------------- 1 | package com.packt.myproject 2 | 3 | import com.packt.myproject.constants.Foo 4 | import com.packt.otherproject.Foo as Foo2 5 | 6 | fun doubleFoo() { 7 | val foo1 = Foo() 8 | val foo2 = Foo2() 9 | } -------------------------------------------------------------------------------- /Chapter07/src/main/kotlin/com/packt/otherproject/Foo.kt: -------------------------------------------------------------------------------- 1 | package com.packt.otherproject 2 | 3 | class Foo -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.1.ParameterizedFunctions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter8 2 | 3 | fun random(one: T, two: T, three: T): T = TODO() 4 | 5 | fun put(key: K, value: V): Unit = TODO() 6 | 7 | fun main() { 8 | val str: String = random("hello", "wilkommen", "bonjour") 9 | val any: Any = random("a", 1, false) 10 | } -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.2.ParameterizedTypes.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter8 2 | 3 | class Sequence 4 | 5 | class Dictionary 6 | 7 | fun example() { 8 | val seq = Sequence() 9 | } -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.5.Nothing.kt: -------------------------------------------------------------------------------- 1 | interface Marshaller { 2 | fun marshall(json: String): T? 3 | } 4 | 5 | object NoopMarshaller : Marshaller { 6 | override fun marshall(json: String) = null 7 | } -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.6.TypeProjection.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter8 2 | 3 | fun isSafe(crate: Crate): Boolean = crate.elements.all { it.isSafeToEat() } 4 | 5 | fun usingTypeProjection() { 6 | val oranges = Crate(mutableListOf(Orange(), Orange())) 7 | isSafe(oranges) 8 | } 9 | 10 | interface Listener2 { 11 | fun onNext(t: T): Unit 12 | } 13 | 14 | class EventStream2(val listener: Listener2) { 15 | fun start(): Unit = TODO() 16 | fun stop(): Unit = TODO() 17 | } -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.7.Erasure.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter8 2 | 3 | fun printInts(list: Set): Unit { 4 | for (int in list) println(int) 5 | } 6 | 7 | fun printStrings(list: Set): Unit { 8 | for (string in list) println(string) 9 | } 10 | 11 | fun > max(list: List): T { 12 | var max = list.first() 13 | for (t in list) { 14 | if (t > max) 15 | max = t 16 | } 17 | return max 18 | } -------------------------------------------------------------------------------- /Chapter08/chapter8/src/main/kotlin/com/packt/chapter8/8.8.Reification.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter8 2 | 3 | inline fun runtimeType(): Unit { 4 | println("My type parameter is " + T::class.qualifiedName) 5 | } 6 | 7 | inline fun List.collect(): List { 8 | return this.filter { it is T }.map { it as T } 9 | } 10 | 11 | fun collectExample() { 12 | val list = listOf("green", false, 100, "blue") 13 | val strings = list.collect() 14 | } 15 | 16 | inline fun printT(any: Any): Unit { 17 | if (any is T) println("I am a tee: $any") 18 | } 19 | 20 | fun main(args: Array) { 21 | printT(123) 22 | } -------------------------------------------------------------------------------- /Chapter09/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter09/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'properties' 2 | 3 | -------------------------------------------------------------------------------- /Chapter09/src/main/java/com/programming/kotlin/chapter09/Sensor.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09; 2 | 3 | public class Sensor { 4 | private final String id; 5 | private final double value; 6 | 7 | public Sensor(String id, double value) { 8 | this.id = id; 9 | this.value = value; 10 | } 11 | 12 | public String getId() { 13 | return id; 14 | } 15 | 16 | public double getValue() { 17 | return value; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Chapter09/src/main/kotlin/com/programming/kotlin/chapter09/BlogEntry.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09 2 | 3 | import org.joda.time.DateTime 4 | import java.net.URI 5 | 6 | /** 7 | * Created by stepi on 15/10/16. 8 | */ 9 | 10 | data class BlogEntry(var title: String, 11 | var description: String, 12 | val publishTime: DateTime, 13 | var approved: Boolean?, 14 | val lastUpdated: DateTime, 15 | val url: URI, 16 | var comments: Int?, 17 | var tags: List, 18 | var email: String?) -------------------------------------------------------------------------------- /Chapter09/src/main/kotlin/com/programming/kotlin/chapter09/Either.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09 2 | 3 | sealed abstract class Either { 4 | //data class Left(val value: L) : Either() 5 | //data class Right(val value: R) : Either() 6 | } -------------------------------------------------------------------------------- /Chapter09/src/main/kotlin/com/programming/kotlin/chapter09/Email.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09 2 | 3 | data class Email(var to:String = "", 4 | var subject:String="", 5 | var content:String="") 6 | -------------------------------------------------------------------------------- /Chapter09/src/main/kotlin/com/programming/kotlin/chapter09/SensorExtension.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09 2 | 3 | operator fun Sensor.component1()= this.id 4 | 5 | operator fun Sensor.component2()=this.value -------------------------------------------------------------------------------- /Chapter09/src/main/kotlin/com/programming/kotlin/chapter09/Vector3.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter09 2 | 3 | class Vector3(val x:Double, val y:Double, val z:Double){ 4 | operator fun component1()=x 5 | operator fun component2()=y 6 | operator fun component3()=z 7 | } -------------------------------------------------------------------------------- /Chapter10/gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.incremental=true -------------------------------------------------------------------------------- /Chapter10/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'chapter10' 2 | 3 | -------------------------------------------------------------------------------- /Chapter10/src/main/java/com/programming/kotlin/chapter10/CollectionsJ.java: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter10; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by stepi on 29/10/16. 8 | */ 9 | public class CollectionsJ { 10 | public static void arrays() { 11 | int[] intArray = new int[]{1, 2, 3, 4}; 12 | } 13 | 14 | public static void countries() { 15 | String[] countries = new String[]{"UK", "Germany", "Italy"}; 16 | for (String country : countries) { 17 | System.out.print(country + ";"); 18 | } 19 | } 20 | 21 | public static void dangerous(Collection l) { 22 | l.add(1000L); 23 | } 24 | 25 | public static void dangerousCall(Collection l) { 26 | l.add(1000); 27 | } 28 | 29 | public static void dangerousCallMap(Map map){ 30 | map.put("newKey!", "newValue!"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Chapter10/src/main/kotlin/com/programming/kotlin/chapter10/IndexedAccess.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter10 2 | 3 | fun indexedAccess():Unit{ 4 | val capitals = listOf("London", "Tokyo", "Instambul", "Bucharest") 5 | capitals[2] //Tokyo 6 | //capitals[100] java.lang.ArrayIndexOutOfBoundException 7 | 8 | val countries = mapOf("BRA" to "Brazil", "ARG" to "Argentina", "ITA" to "Italy") 9 | countries["BRA"] //Brazil 10 | countries["UK"] //null 11 | 12 | } -------------------------------------------------------------------------------- /Chapter10/src/main/kotlin/com/programming/kotlin/chapter10/Program.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter10 2 | 3 | import java.util.* 4 | import kotlin.reflect.jvm.jvmName 5 | 6 | fun main(args: Array): Unit { 7 | println("Programming Kotlin:Chapter10") 8 | 9 | val jlist = ArrayList() 10 | 11 | jlist.add("sample") 12 | itWorks(jlist) 13 | itWorks(Collections.singletonList(1)) 14 | 15 | arrays() 16 | maps() 17 | sets() 18 | lists() 19 | readonly() 20 | indexedAccess() 21 | sequences() 22 | } 23 | 24 | fun itWorks(list: List): Unit { 25 | println("Java Class Type:" + list.javaClass.canonicalName) 26 | } -------------------------------------------------------------------------------- /Chapter10/src/main/kotlin/com/programming/kotlin/chapter10/ReadOnly.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter10 2 | 3 | fun readonly(){ 4 | val carManufacturers: MutableList = mutableListOf("Masserati", "Aston Martin","McLaren","Ferrari","Koenigsegg") 5 | val carsView: List = carManufacturers 6 | 7 | carManufacturers.add("Lamborghini") 8 | println("Cars View:$carsView") 9 | } -------------------------------------------------------------------------------- /Chapter10/src/main/resources/afile.txt: -------------------------------------------------------------------------------- 1 | Kotlin 2 | is 3 | awesome! -------------------------------------------------------------------------------- /Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.11.Resources.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter11 2 | 3 | import io.kotlintest.specs.StringSpec 4 | 5 | class ResourceExample : StringSpec() { 6 | 7 | val input = autoClose(javaClass.getResourceAsStream("/orders.csv")) 8 | 9 | init { 10 | "your test case" { 11 | // use input stream here 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.5.Inspectors.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter11 2 | 3 | import io.kotlintest.specs.StringSpec 4 | 5 | val kings = listOf("Stephen I", "Henry I", "Henry II", "Henry III", "William I", "William II") 6 | 7 | class InspectorTests : StringSpec() { 8 | init { 9 | 10 | "all kings should have a regal number" { 11 | forAll(kings) { 12 | it should endWith("I") 13 | } 14 | } 15 | 16 | "only one king has the name Stephen" { 17 | forOne(kings) { 18 | it should startWith("Stephen") 19 | } 20 | } 21 | 22 | "some kings have regal number II" { 23 | forSome(kings) { 24 | it should endWith("II") 25 | } 26 | } 27 | 28 | "at least one King has the name Henry" { 29 | forAtLeastOne(kings) { 30 | it should startWith("Henry") 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.6.ProjectConfig.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter11 2 | 3 | import com.sun.net.httpserver.HttpServer 4 | import io.kotlintest.ProjectConfig 5 | import java.net.InetSocketAddress 6 | import java.util.concurrent.Executors 7 | 8 | object MyProjectConfig : ProjectConfig() { 9 | 10 | var server: HttpServer? = null 11 | 12 | override fun beforeAll() { 13 | val addr = InetSocketAddress(8080) 14 | val server = HttpServer.create(addr, 0) 15 | server.executor = Executors.newCachedThreadPool() 16 | server.start() 17 | println("Server is listening on port 8080") 18 | } 19 | 20 | override fun afterAll() { 21 | server!!.stop(0) 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.8.TableDrivenTesting.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter11 2 | 3 | import io.kotlintest.specs.StringSpec 4 | 5 | class TableExample : StringSpec() { 6 | init { 7 | 8 | "example of booleans" { 9 | 10 | val table = table( 11 | headers("a", "b", "c"), 12 | row(true, true, true), 13 | row(true, false, true), 14 | row(true, false, false) 15 | ) 16 | 17 | forAll(table) { a, b, c -> 18 | a shouldBe true 19 | if (b) 20 | c shouldBe true 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter11/chapter11/src/main/kotlin/com/packt/chapter11/11.9.Eventually.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter11 2 | 3 | import io.kotlintest.Duration.Companion.seconds 4 | import io.kotlintest.Eventually 5 | import io.kotlintest.specs.ShouldSpec 6 | import io.kotlintest.specs.WordSpec 7 | import java.util.concurrent.CountDownLatch 8 | import java.util.concurrent.TimeUnit 9 | 10 | fun createFile(file: String, onComplete: () -> Unit = {}): Unit { 11 | 12 | } 13 | 14 | fun createFileCallbackExample() { 15 | val latch = CountDownLatch(1) 16 | createFile("/home/davidcopperfield.txt", { latch.countDown() }) 17 | latch.await(1, TimeUnit.MINUTES) 18 | // continue with test 19 | } 20 | 21 | fun createFileThreadSleepExample() { 22 | createFile("/home/davidcopperfield.txt") 23 | Thread.sleep(5000) 24 | // continue with test 25 | } 26 | 27 | class FileCreateWithEventually : ShouldSpec(), Eventually { 28 | 29 | init { 30 | should("create file") { 31 | eventually(60.seconds) { 32 | createFile("/home/davidcopperfield.txt") 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Chapter12/cassandra-config/src/assembly/conductr-bundle.xml: -------------------------------------------------------------------------------- 1 | 4 | conductr-bundle 5 | 6 | zip 7 | 8 | cassandra-config-v1 9 | 10 | 11 | 12 | 13 | src/bundle 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter12/cassandra-config/src/bundle/bundle.conf: -------------------------------------------------------------------------------- 1 | name = "cassandra" 2 | system = "cassandra" 3 | components.cassandra = { 4 | endpoints = { 5 | "cas_native" = { 6 | bind-protocol = "tcp" 7 | bind-port = 0 8 | services = ["tcp://:9042/cas_native"] 9 | }, 10 | // 'cas_rpc' endpoint need to be declared to override the endpoint from the cassandra bundle itself 11 | "cas_rpc" = { 12 | bind-protocol = "tcp" 13 | bind-port = 0 14 | services = [] 15 | }, 16 | "cas_storage" = { 17 | bind-protocol = "tcp" 18 | bind-port = 7000 19 | services = [] 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter12/cassandra-config/src/bundle/runtime-config.sh: -------------------------------------------------------------------------------- 1 | # Demonstrate providing an entirely new configuration directory 2 | CURRENT_PATH=`dirname "$0"` 3 | export $CASSANDRA_CONF=$CURRENT_PATH/cassandra-conf -------------------------------------------------------------------------------- /Chapter12/hello-api/src/main/kotlin/com.programming.kotlin.chapter12.hello.api/GreetingMessage.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.api 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator 4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize 5 | 6 | @JsonDeserialize 7 | data class GreetingMessage @JsonCreator constructor(val message: String) -------------------------------------------------------------------------------- /Chapter12/hello-api/src/main/kotlin/com.programming.kotlin.chapter12.hello.api/Jackson.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.api 2 | 3 | import com.fasterxml.jackson.module.kotlin.* 4 | import com.fasterxml.jackson.databind.ObjectMapper 5 | 6 | object Jackson{ 7 | val mapper: ObjectMapper = { 8 | ObjectMapper().registerKotlinModule() 9 | }() 10 | } -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/bundle/bundle.conf: -------------------------------------------------------------------------------- 1 | version = "1" 2 | name = "hello" 3 | compatibilityVersion = "1" 4 | system = "hello" 5 | systemVersion = "1" 6 | nrOfCpus = 0.1 7 | memory = 268435456 8 | diskSpace = 200000000 9 | roles = ["web"] 10 | components = { 11 | hello = { 12 | description = "hello" 13 | file-system-type = "universal" 14 | start-command = ["hello/bin/hello"] 15 | endpoints = { 16 | "hello" = { 17 | bind-protocol = "http" 18 | bind-port = 0 19 | services = ["http://:9000/hello","http://:9000/api/hello?preservePath"] 20 | }, 21 | "akka-remote" = { 22 | bind-protocol = "tcp" 23 | bind-port = 0 24 | services = [] 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/java/com/programming/kotlin/chapter12/hello/impl/HelloModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Lightbend Inc. 3 | *//* 4 | 5 | package com.programming.kotlin.chapter12.hello.impl; 6 | 7 | import com.google.inject.AbstractModule; 8 | import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; 9 | import com.programming.kotlin.chapter12.hello.api.HelloService; 10 | 11 | */ 12 | /** 13 | * The module that binds the HelloService so that it can be served. 14 | *//* 15 | 16 | public class HelloModule extends AbstractModule implements ServiceGuiceSupport { 17 | @Override 18 | protected void configure() { 19 | bindServices(serviceBinding(HelloService.class, HelloServiceImpl.class)); 20 | } 21 | } 22 | */ 23 | -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/kotlin/com.programming.kotlin.chapter12.hello.impl/HelloCommand.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.impl 2 | 3 | import akka.Done 4 | import com.fasterxml.jackson.annotation.JsonCreator 5 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize 6 | import com.lightbend.lagom.javadsl.persistence.PersistentEntity 7 | import com.lightbend.lagom.serialization.CompressedJsonable 8 | import com.lightbend.lagom.serialization.Jsonable 9 | import java.util.* 10 | 11 | interface HelloCommand : Jsonable 12 | 13 | @JsonDeserialize 14 | data class UseGreetingMessage @JsonCreator constructor(val message: String) : HelloCommand, CompressedJsonable, PersistentEntity.ReplyType 15 | 16 | @JsonDeserialize 17 | data class Hello @JsonCreator constructor(val name: String, val organization: Optional) : HelloCommand, PersistentEntity.ReplyType 18 | -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/kotlin/com.programming.kotlin.chapter12.hello.impl/HelloEvent.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.impl 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator 4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize 5 | import com.lightbend.lagom.serialization.Jsonable 6 | 7 | interface HelloEvent : Jsonable 8 | 9 | @JsonDeserialize 10 | data class GreetingMessageChanged @JsonCreator constructor(val message: String) : HelloEvent 11 | -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/kotlin/com.programming.kotlin.chapter12.hello.impl/HelloModule.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.impl 2 | 3 | import com.google.inject.AbstractModule 4 | import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport 5 | import com.programming.kotlin.chapter12.hello.api.HelloService 6 | 7 | class HelloModule : AbstractModule(), ServiceGuiceSupport { 8 | override fun configure() { 9 | bindServices(serviceBinding(HelloService::class.java, HelloServiceImpl::class.java)) 10 | } 11 | } -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/kotlin/com.programming.kotlin.chapter12.hello.impl/HelloState.kt: -------------------------------------------------------------------------------- 1 | package com.programming.kotlin.chapter12.hello.impl 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator 4 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize 5 | import com.lightbend.lagom.serialization.CompressedJsonable 6 | 7 | @JsonDeserialize 8 | data class HelloState @JsonCreator constructor(val message: String, val timestamp: String) : CompressedJsonable -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2016 Lightbend Inc. 3 | # 4 | play.modules.enabled += com.programming.kotlin.chapter12.hello.impl.HelloModule 5 | 6 | lagom.persistence.ask-timeout=10s -------------------------------------------------------------------------------- /Chapter12/hello-impl/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %date{ISO8601} %-5level %logger - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter12/integration-tests/src/test/resources/application.conf: -------------------------------------------------------------------------------- 1 | # Because the client factory needs it 2 | -------------------------------------------------------------------------------- /Chapter12/integration-tests/src/test/resources/logback-test.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | %date{ISO8601} %-5level %logger - %msg%n 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter12/stream-api/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | com.programming.kotlin 5 | chapter12 6 | 1.0-SNAPSHOT 7 | 8 | 9 | stream-api 10 | 11 | jar 12 | 13 | 14 | 15 | com.lightbend.lagom 16 | lagom-javadsl-api_2.11 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter12/stream-impl/src/bundle/bundle.conf: -------------------------------------------------------------------------------- 1 | version = "1" 2 | name = "stream" 3 | compatibilityVersion = "1" 4 | system = "stream" 5 | systemVersion = "1" 6 | nrOfCpus = 0.1 7 | memory = 268435456 8 | diskSpace = 200000000 9 | roles = ["web"] 10 | components = { 11 | stream = { 12 | description = "stream" 13 | file-system-type = "universal" 14 | start-command = ["stream/bin/stream"] 15 | endpoints = { 16 | "stream" = { 17 | bind-protocol = "http" 18 | bind-port = 0 19 | services = ["http://:9000/stream","http://:9000/stream?preservePath"] 20 | }, 21 | "akka-remote" = { 22 | bind-protocol = "tcp" 23 | bind-port = 0 24 | services = [] 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter12/stream-impl/src/main/java/com/programming/kotlin/chapter12/stream/impl/StreamModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Lightbend Inc. 3 | */ 4 | package com.programming.kotlin.chapter12.stream.impl; 5 | 6 | import com.google.inject.AbstractModule; 7 | import com.lightbend.lagom.javadsl.server.ServiceGuiceSupport; 8 | import com.programming.kotlin.chapter12.hello.api.HelloService; 9 | import com.programming.kotlin.chapter12.stream.api.StreamService; 10 | 11 | /** 12 | * The module that binds the StreamService so that it can be served. 13 | */ 14 | public class StreamModule extends AbstractModule implements ServiceGuiceSupport { 15 | @Override 16 | protected void configure() { 17 | // Bind the StreamService service 18 | bindServices(serviceBinding(StreamService.class, StreamServiceImpl.class)); 19 | // Bind the HelloService client 20 | bindClient(HelloService.class); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Chapter12/stream-impl/src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2016 Lightbend Inc. 3 | # 4 | play.modules.enabled += com.programming.kotlin.chapter12.stream.impl.StreamModule 5 | -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.10.CyclicBarrier.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import java.nio.file.Files 4 | import java.nio.file.Path 5 | import java.nio.file.StandardCopyOption 6 | import java.util.concurrent.CyclicBarrier 7 | import java.util.concurrent.Executors 8 | 9 | fun copyUsingBarrier(inputFiles: List, outputDirectories: List) { 10 | 11 | val executor = Executors.newFixedThreadPool(outputDirectories.size) 12 | val barrier = CyclicBarrier(outputDirectories.size) 13 | 14 | for (dir in outputDirectories) { 15 | executor.submit { 16 | CopyTask(dir, inputFiles, barrier) 17 | } 18 | } 19 | } 20 | 21 | class CopyTask(val dir: Path, 22 | val paths: List, 23 | val barrier: CyclicBarrier) : Runnable { 24 | 25 | override fun run() { 26 | for (path in paths) { 27 | val dest = dir.resolve(path) 28 | Files.copy(path, dest, StandardCopyOption.REPLACE_EXISTING) 29 | barrier.await() 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.11.Asynchronous.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | data class Card(val number: String) 4 | 5 | data class Order(val id: String, val card: Card) 6 | 7 | fun persistOrder(order: Order, callback: (String) -> Unit): Unit = TODO() 8 | fun chargeCard(card: Card, callback: (Boolean) -> Unit): Unit = TODO() 9 | fun printInvoice(order: Order, callback: (Unit) -> Unit): Unit = TODO() 10 | 11 | fun processOrder(order: Order) { 12 | persistOrder(order, { 13 | println("Order has been saved; charging card") 14 | chargeCard(order.card, { result -> 15 | if (result) { 16 | println("Order has been charged; printing invoice") 17 | printInvoice(order, { 18 | println("Invoice has been printed") 19 | }) 20 | } 21 | }) 22 | }) 23 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.4.Executors.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import java.util.concurrent.Callable 4 | import java.util.concurrent.Executors 5 | import java.util.concurrent.Future 6 | import java.util.concurrent.TimeUnit 7 | 8 | fun main(args: Array) { 9 | val executor = Executors.newFixedThreadPool(4) 10 | for (k in 1..10) { 11 | executor.submit { 12 | println("Processing element $k on thread ${Thread.currentThread()}") 13 | } 14 | } 15 | executor.shutdown() 16 | executor.awaitTermination(1, TimeUnit.MINUTES) 17 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.5.RaceConditions.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import java.util.concurrent.locks.ReentrantLock 4 | import kotlin.concurrent.withLock 5 | 6 | fun syncExample() { 7 | 8 | val obj = Any() 9 | synchronized(obj) { 10 | 11 | } 12 | } 13 | 14 | fun lockOrNot() { 15 | val lock = ReentrantLock() 16 | if (lock.tryLock()) { 17 | println("I have the lock") 18 | lock.unlock() 19 | } else { 20 | println("I do not have the lock") 21 | } 22 | } 23 | 24 | fun lockOrInterrupt() { 25 | val lock = ReentrantLock() 26 | try { 27 | lock.lockInterruptibly() 28 | println("I have the lock") 29 | lock.unlock() 30 | } catch (e: InterruptedException) { 31 | println("I was interrupted") 32 | } 33 | } 34 | 35 | fun kotlinLock() { 36 | val lock = ReentrantLock() 37 | lock.withLock { 38 | println("I have the lock") 39 | } 40 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.7.ConcurrentCollections.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import java.util.* 4 | import java.util.concurrent.LinkedBlockingQueue 5 | import kotlin.concurrent.thread 6 | 7 | fun boundedBuffer() { 8 | val buffer = LinkedBlockingQueue() 9 | 10 | thread { 11 | val random = Random() 12 | while (true) { 13 | buffer.put(random.nextInt()) 14 | } 15 | } 16 | 17 | thread { 18 | while (true) { 19 | val item = buffer.take(0) 20 | println("Consumed item $item") 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.8.Atomics.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import counter 4 | import java.sql.Connection 5 | import java.util.concurrent.atomic.AtomicLong 6 | import java.util.concurrent.atomic.AtomicReference 7 | import kotlin.concurrent.thread 8 | 9 | fun atomicCounters() { 10 | val counter = AtomicLong(0) 11 | (1..8).forEach { 12 | thread { 13 | while (true) { 14 | val id = counter.incrementAndGet() 15 | println("Creating item with id $id") 16 | } 17 | } 18 | } 19 | } 20 | 21 | fun openConnection(): Connection = TODO() 22 | 23 | fun atomicReferences() { 24 | val ref = AtomicReference() 25 | (1..8).forEach { 26 | thread { 27 | ref.compareAndSet(null, openConnection()) 28 | val conn = ref.get() 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Chapter13/src/main/kotlin/com/packt/chapter13/13.9.CountdownLatch.kt: -------------------------------------------------------------------------------- 1 | package com.packt.chapter13 2 | 3 | import java.util.concurrent.CountDownLatch 4 | import java.util.concurrent.Executors 5 | 6 | data class Feed(val name: String, val url: String) 7 | 8 | fun processFeed(feed: Feed): Unit { 9 | println("Processing feed ${feed.name}") 10 | } 11 | 12 | fun sendNotification(): Unit { 13 | println("Sending notification") 14 | } 15 | 16 | fun countDownLatchExample() { 17 | 18 | val feeds = listOf( 19 | Feed("Great Vegetable Store", "http://www.greatvegstore.co.uk/items.xml"), 20 | Feed("Super Food Shop", "http://www.superfoodshop.com/products.csv") 21 | ) 22 | 23 | val latch = CountDownLatch(feeds.size) 24 | 25 | val executor = Executors.newCachedThreadPool() 26 | for (feed in feeds) { 27 | executor.submit { 28 | processFeed(feed) 29 | latch.countDown() 30 | } 31 | } 32 | 33 | latch.await() 34 | println("All feeds completed") 35 | sendNotification() 36 | } -------------------------------------------------------------------------------- /Chapter14/async.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.async 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | runBlocking { 7 | val deferred = async { 8 | println("Computing value") 9 | delay(1000) 10 | "result" 11 | } 12 | val result = deferred.await() 13 | println("The result is $result") 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter14/cancel_children.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | suspend fun child1() { 7 | println("Starting child 1") 8 | delay(2000) 9 | println("Completing child 1") 10 | } 11 | suspend fun child2() { 12 | println("Starting child 2") 13 | delay(1000) 14 | throw RuntimeException("Boom") 15 | } 16 | try { 17 | runBlocking { 18 | launch { 19 | child1() 20 | } 21 | launch { 22 | child2() 23 | } 24 | } 25 | } catch (e: Exception) { 26 | println("Failed with ${e.message}") 27 | } 28 | } -------------------------------------------------------------------------------- /Chapter14/child_failure.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | suspend fun child1() { 7 | println("Starting child 1") 8 | delay(2000) 9 | println("Completing child 1") 10 | } 11 | suspend fun child2() { 12 | println("Starting child 2") 13 | delay(1000) 14 | throw RuntimeException("Boom") 15 | } 16 | try { 17 | runBlocking { 18 | launch { 19 | child1() 20 | } 21 | launch { 22 | child2() 23 | } 24 | } 25 | } catch (e: Exception) { 26 | println("Failed with ${e.message}") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter14/concurrent_ecommerce.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | import kotlin.system.measureTimeMillis 5 | 6 | fun main() { 7 | 8 | suspend fun printShippingLabels() { 9 | delay(3000) 10 | println("After three seconds") 11 | } 12 | 13 | suspend fun processPayment() { 14 | delay(2000) 15 | println("Order after two seconds") 16 | } 17 | 18 | suspend fun sendEmails() { 19 | delay(1000) 20 | println("Payment after one second") 21 | } 22 | 23 | println("Starting") 24 | val time = measureTimeMillis { 25 | runBlocking { 26 | launch { 27 | printShippingLabels() 28 | } 29 | launch { 30 | processPayment() 31 | } 32 | launch { 33 | sendEmails() 34 | } 35 | } 36 | println("runBlocking done") 37 | } 38 | println("Completed in $time ms") 39 | } -------------------------------------------------------------------------------- /Chapter14/concurrent_ecommerce_async.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.async 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.runBlocking 4 | import kotlin.system.measureTimeMillis 5 | 6 | fun main() { 7 | 8 | suspend fun fetchOrder(): String { 9 | delay(3000) 10 | return "Order 123" 11 | } 12 | 13 | suspend fun fetchAddress(): String { 14 | delay(2000) 15 | return "10 Downing Street" 16 | } 17 | 18 | suspend fun fetchUsername(): String { 19 | delay(1000) 20 | return "Prime Minster" 21 | } 22 | 23 | println("Starting") 24 | val time = measureTimeMillis { 25 | runBlocking { 26 | val order = async { 27 | fetchOrder() 28 | } 29 | val address = async { 30 | fetchAddress() 31 | } 32 | val username = async { 33 | fetchUsername() 34 | } 35 | println("Shipping ${order.await()} to ${username.await()} at ${address.await()}") 36 | } 37 | } 38 | println("Completed in $time ms") 39 | } -------------------------------------------------------------------------------- /Chapter14/debugging.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | fun logger(message: String) = println("${Thread.currentThread().name} $message") 8 | val jobs = (1..3).map { 9 | GlobalScope.launch { 10 | repeat(3) { 11 | delay(300) 12 | logger("I'm working hard") 13 | } 14 | } 15 | } 16 | runBlocking { 17 | logger("Starting calculation") 18 | jobs.forEach { it.join() } 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter14/debugging_named.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.CoroutineName 2 | import kotlinx.coroutines.GlobalScope 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.launch 5 | import kotlinx.coroutines.runBlocking 6 | 7 | fun main() { 8 | fun logger(message: String) = println("${Thread.currentThread().name} $message") 9 | val jobs = listOf("parser", "crawler", "lexer").map { 10 | GlobalScope.launch(CoroutineName(it)) { 11 | repeat(3) { 12 | delay(300) 13 | logger("I'm working hard") 14 | } 15 | } 16 | } 17 | runBlocking { 18 | logger("Starting calculation") 19 | jobs.forEach { it.join() } 20 | } 21 | } -------------------------------------------------------------------------------- /Chapter14/dispatcher_default.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Dispatchers 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | runBlocking { 7 | println("A: " + Thread.currentThread().name) 8 | launch(Dispatchers.Default) { 9 | println("B: " + Thread.currentThread().name) 10 | } 11 | launch { 12 | println("C: " + Thread.currentThread().name) 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter14/dispatcher_io.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Dispatchers 2 | import kotlinx.coroutines.runBlocking 3 | 4 | fun main() { 5 | runBlocking(Dispatchers.IO) { 6 | println(Thread.currentThread().name) 7 | } 8 | } -------------------------------------------------------------------------------- /Chapter14/dispatcher_wrapper.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.asCoroutineDispatcher 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | import java.util.concurrent.Executors.newSingleThreadExecutor 5 | 6 | fun main() { 7 | runBlocking { 8 | val executor = newSingleThreadExecutor { r -> Thread(r, "my-executor-dispatcher") } 9 | val dispatcher = executor.asCoroutineDispatcher() 10 | launch(dispatcher) { 11 | println(Thread.currentThread().name) 12 | } 13 | launch { 14 | println(Thread.currentThread().name) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter14/exception_handler.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.CoroutineExceptionHandler 2 | import kotlinx.coroutines.GlobalScope 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.launch 5 | import kotlinx.coroutines.runBlocking 6 | 7 | fun main() { 8 | val handler = CoroutineExceptionHandler { context, throwable -> 9 | println("Intercepted exception of type ${throwable.javaClass.simpleName}") 10 | } 11 | runBlocking { 12 | val job = GlobalScope.launch(handler) { 13 | launch { 14 | println("Starting first child") 15 | delay(1000) 16 | println("First child completed") 17 | } 18 | launch { 19 | println("Second child throwing exception") 20 | delay(100) 21 | throw IndexOutOfBoundsException() 22 | } 23 | } 24 | job.join() 25 | } 26 | } -------------------------------------------------------------------------------- /Chapter14/exception_handler_await.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.CoroutineExceptionHandler 2 | import kotlinx.coroutines.GlobalScope 3 | import kotlinx.coroutines.async 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | val handler = CoroutineExceptionHandler { context, throwable -> 8 | println("Intercepted exception of type ${throwable.javaClass.simpleName}") 9 | } 10 | runBlocking { 11 | val deferred = GlobalScope.async(handler) { 12 | throw IndexOutOfBoundsException() 13 | } 14 | deferred.await() 15 | } 16 | } -------------------------------------------------------------------------------- /Chapter14/first_coroutine.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | 5 | fun main() { 6 | GlobalScope.launch { 7 | delay(1000) 8 | println("I am a coroutine") 9 | } 10 | println("I am the main thread") 11 | Thread.sleep(2000) 12 | } 13 | -------------------------------------------------------------------------------- /Chapter14/intro.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Dispatchers 2 | import kotlinx.coroutines.GlobalScope 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.launch 5 | 6 | fun main() { 7 | GlobalScope.launch { 8 | // create a new global level coroutine 9 | delay(1000L) // wait for 1 second 10 | println("World!") 11 | } 12 | println("Hello,") // main thread continues while coroutine is delayed 13 | Thread.sleep(2000L) // block main thread to keep JVM alive 14 | GlobalScope.launch(context = Dispatchers.IO) { 15 | // will get dispatched to DefaultDispatcher 16 | println("Default : I'm working in thread ${Thread.currentThread().name}") 17 | } 18 | 19 | 20 | } -------------------------------------------------------------------------------- /Chapter14/jobs.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | var x = 0 8 | val job = GlobalScope.launch { 9 | while (true) { 10 | x += 1 11 | delay(10) 12 | println(x) 13 | } 14 | } 15 | runBlocking { 16 | delay(100) 17 | job.cancel() 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter14/join.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | val job = GlobalScope.launch { 8 | delay(1000L) 9 | println("Hello") 10 | } 11 | runBlocking { 12 | job.join() 13 | println("World") 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Chapter14/lazy.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.CoroutineStart 2 | import kotlinx.coroutines.GlobalScope 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.launch 5 | import kotlinx.coroutines.runBlocking 6 | 7 | fun main() { 8 | val job = GlobalScope.launch(start = CoroutineStart.LAZY) { 9 | delay(100) 10 | println("World") 11 | } 12 | runBlocking { 13 | delay(1000) 14 | println("Hello") 15 | job.join() 16 | } 17 | } -------------------------------------------------------------------------------- /Chapter14/nested_coroutines.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | runBlocking { 7 | println("Parent starting") 8 | launch { 9 | println("Child a starting") 10 | delay(100) 11 | println("Child a complete") 12 | } 13 | launch { 14 | println("Child b starting") 15 | delay(100) 16 | println("Child b complete") 17 | } 18 | println("Parent complete") 19 | } 20 | println("Parent returned") 21 | } -------------------------------------------------------------------------------- /Chapter14/parent_cancellation.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Job 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | runBlocking { 8 | var child: Job? = null 9 | val job = launch { 10 | child = launch { 11 | delay(1000) 12 | println("I am a child") 13 | } 14 | } 15 | delay(100) 16 | job.cancel() 17 | println("Cancelled=" + child!!.isCancelled) 18 | } 19 | } -------------------------------------------------------------------------------- /Chapter14/parent_failure.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Job 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | import java.lang.Exception 6 | 7 | fun main() { 8 | var job: Job? = null 9 | try { 10 | runBlocking { 11 | job = launch { 12 | delay(1000) 13 | println("I am a child") 14 | } 15 | delay(100) 16 | throw RuntimeException("boom") 17 | } 18 | } catch (e: Exception) { 19 | println("Catching exception") 20 | } 21 | println("Cancelled=" + job!!.isCancelled) 22 | } -------------------------------------------------------------------------------- /Chapter14/runBlocking.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.runBlocking 3 | 4 | fun main() { 5 | runBlocking { 6 | delay(1000) 7 | println("Hello World") 8 | } 9 | println("Done") 10 | } -------------------------------------------------------------------------------- /Chapter14/second_coroutine.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | 5 | fun main() { 6 | GlobalScope.launch { 7 | delay(1000) 8 | println("Hello World") 9 | } 10 | println("Done") 11 | } 12 | -------------------------------------------------------------------------------- /Chapter14/sequential.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.runBlocking 3 | 4 | fun main() { 5 | suspend fun a() { 6 | delay(100) 7 | println("a") 8 | } 9 | suspend fun b() { 10 | delay(100) 11 | println("b") 12 | } 13 | runBlocking { 14 | a() 15 | b() 16 | println("Done") 17 | } 18 | } -------------------------------------------------------------------------------- /Chapter14/sequential_awaits.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.async 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | suspend fun echo(msg: String): String { 7 | println("Suspending echo") 8 | delay(100) 9 | println("Resumed echo") 10 | return msg 11 | } 12 | runBlocking { 13 | val foo = async { 14 | echo("foo") 15 | } 16 | println("Calling await") 17 | println(foo.await()) 18 | val bar = async { 19 | echo("bar") 20 | } 21 | println("Calling await") 22 | println(bar.await()) 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter14/sequential_ecommerce.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.runBlocking 3 | import kotlin.system.measureTimeMillis 4 | 5 | fun main() { 6 | 7 | suspend fun printShippingLabels() { 8 | delay(3000) 9 | println("After three seconds") 10 | } 11 | 12 | suspend fun processPayment() { 13 | delay(2000) 14 | println("Order after two seconds") 15 | } 16 | 17 | suspend fun sendEmails() { 18 | delay(1000) 19 | println("Payment after one second") 20 | } 21 | 22 | println("Starting") 23 | val time = measureTimeMillis { 24 | runBlocking { 25 | printShippingLabels() 26 | processPayment() 27 | sendEmails() 28 | } 29 | println("runBlocking done") 30 | } 31 | println("Completed in $time ms") 32 | } -------------------------------------------------------------------------------- /Chapter14/sequential_with_input.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.runBlocking 2 | import kotlin.random.Random 3 | 4 | fun main() { 5 | suspend fun a(): Int = Random.nextInt() 6 | suspend fun b(a: Int) { 7 | println("Using $a") 8 | } 9 | runBlocking { 10 | val a = a() 11 | b(a) 12 | } 13 | } -------------------------------------------------------------------------------- /Chapter14/supervisor_scope.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.delay 2 | import kotlinx.coroutines.launch 3 | import kotlinx.coroutines.runBlocking 4 | import kotlinx.coroutines.supervisorScope 5 | import kotlinx.coroutines.withContext 6 | 7 | fun main() { 8 | suspend fun child1() { 9 | println("Starting child 1") 10 | delay(100) 11 | throw RuntimeException("Boom") 12 | } 13 | suspend fun child2() { 14 | println("Starting child 2") 15 | delay(100) 16 | println("Completing child 2") 17 | } 18 | runBlocking { 19 | supervisorScope { 20 | launch { 21 | child1() 22 | } 23 | launch { 24 | child2() 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Chapter14/will_block_before_exit.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | 5 | fun main() { 6 | GlobalScope.launch { 7 | delay(1000) 8 | println("Hello World") 9 | } 10 | Thread.sleep(2000) 11 | println("Done") 12 | } -------------------------------------------------------------------------------- /Chapter14/will_exit.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.GlobalScope 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | 5 | fun main() { 6 | GlobalScope.launch { 7 | delay(1000) 8 | println("Hello World") 9 | } 10 | println("Done") 11 | } -------------------------------------------------------------------------------- /Chapter14/withContext.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.newSingleThreadContext 2 | import kotlinx.coroutines.runBlocking 3 | import kotlinx.coroutines.withContext 4 | 5 | 6 | fun main() { 7 | fun logger(message: String) = println("${Thread.currentThread().name} $message") 8 | runBlocking { 9 | logger("Starting") 10 | withContext(newSingleThreadContext("A")) { 11 | logger("Running in new context") 12 | withContext(newSingleThreadContext("B")) { 13 | logger("Running in new context") 14 | } 15 | } 16 | logger("Completing") 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Chapter15/blocking_calls.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.Dispatchers 2 | import kotlinx.coroutines.runBlocking 3 | import kotlinx.coroutines.withContext 4 | import java.io.ByteArrayOutputStream 5 | import java.io.InputStream 6 | 7 | fun main() { 8 | runBlocking { 9 | val bytes = withContext(Dispatchers.IO) { 10 | javaClass.getResourceAsStream("/largefile.csv").readAllBytes() 11 | } 12 | println("Bytes read") 13 | } 14 | } 15 | 16 | fun InputStream.readAllBytes(): ByteArray { 17 | val buffer = ByteArrayOutputStream() 18 | var byte = read() 19 | while (byte != -1) { 20 | buffer.write(byte) 21 | byte = read() 22 | } 23 | return buffer.toByteArray() 24 | } 25 | -------------------------------------------------------------------------------- /Chapter15/channel_capacity.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.Channel 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | runBlocking { 8 | val channel = Channel(3) 9 | launch { 10 | for (k in 1..5) { 11 | channel.send(k) 12 | println("Sent element $k") 13 | } 14 | } 15 | launch { 16 | repeat(5) { 17 | delay(10) 18 | println("Received element " + channel.receive()) 19 | } 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /Chapter15/channel_conflated.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.Channel 2 | import kotlinx.coroutines.channels.Channel.Factory.CONFLATED 3 | import kotlinx.coroutines.delay 4 | import kotlinx.coroutines.launch 5 | import kotlinx.coroutines.runBlocking 6 | 7 | fun main() { 8 | runBlocking { 9 | val channel = Channel(CONFLATED) 10 | launch { 11 | for (k in 1..1000) { 12 | delay(10) 13 | channel.send(k) 14 | println("Sent element $k") 15 | } 16 | } 17 | launch { 18 | while (true) { 19 | delay(25) 20 | println("Received element " + channel.receive()) 21 | } 22 | } 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Chapter15/channel_iteration.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.Channel 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | runBlocking { 8 | val channel = Channel() 9 | launch { 10 | for (k in 1..5) { 11 | channel.send(k) 12 | println("Sent element $k") 13 | } 14 | println("Closing channel") 15 | channel.close() 16 | } 17 | launch { 18 | for (k in channel) { 19 | println("Received element $k") 20 | } 21 | println("Channel has closed") 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter15/channel_producer.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.consumeEach 2 | import kotlinx.coroutines.channels.produce 3 | import kotlinx.coroutines.runBlocking 4 | 5 | fun main() { 6 | runBlocking { 7 | val channel = produce { 8 | for (k in 1..5) { 9 | send(k) 10 | } 11 | } 12 | channel.consumeEach { println(it) } 13 | println("Done!") 14 | } 15 | } -------------------------------------------------------------------------------- /Chapter15/channel_ticker.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.ticker 2 | import kotlinx.coroutines.runBlocking 3 | import kotlinx.coroutines.withTimeoutOrNull 4 | 5 | fun main() = runBlocking { 6 | val ticker = ticker(delayMillis = 50, initialDelayMillis = 25) 7 | repeat(5) { 8 | val element = withTimeoutOrNull(15) { ticker.receive() } 9 | println("$it: $element") 10 | } 11 | ticker.cancel() // indicate that no more elements are needed 12 | } -------------------------------------------------------------------------------- /Chapter15/channels_rendezvous.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.Channel 2 | import kotlinx.coroutines.delay 3 | import kotlinx.coroutines.launch 4 | import kotlinx.coroutines.runBlocking 5 | 6 | fun main() { 7 | runBlocking { 8 | val channel = Channel() 9 | launch { 10 | println("About to produce an element") 11 | channel.send("foo") 12 | println("Produced element foo") 13 | } 14 | launch { 15 | println("About to receive an element") 16 | delay(100) 17 | println("Received element " + channel.receive()) 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Chapter15/select_closed.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.channels.produce 2 | import kotlinx.coroutines.runBlocking 3 | import kotlinx.coroutines.selects.select 4 | 5 | fun main() { 6 | runBlocking { 7 | val producer = produce { 8 | var x = 1 9 | repeat(3) { 10 | send(x++) 11 | } 12 | } 13 | repeat(4) { 14 | select { 15 | producer.onReceiveOrNull { value -> 16 | if (value == null) 17 | println("The channel has closed") 18 | else 19 | println("$value was produced") 20 | } 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Chapter15/select_deferred.kt: -------------------------------------------------------------------------------- 1 | import kotlinx.coroutines.async 2 | import kotlinx.coroutines.runBlocking 3 | import kotlinx.coroutines.selects.select 4 | 5 | suspend fun crawl(url: String): String = TODO() 6 | fun parse(html: String): Unit = TODO() 7 | 8 | fun main() { 9 | val urls = listOf("..", "..", "..") 10 | runBlocking { 11 | val deferreds = urls.map { 12 | async { 13 | crawl(it) 14 | } 15 | } 16 | select { 17 | deferreds.forEach { 18 | it.onAwait { html -> 19 | parse(html) 20 | } 21 | } 22 | } 23 | } 24 | } 25 | 26 | interface Shape { 27 | val area: Double 28 | } 29 | 30 | class Rectangle(val width: Double, val height: Double) : Shape { 31 | override val area: Double 32 | get() = width * height 33 | 34 | val isSquare: Boolean = width == height 35 | } --------------------------------------------------------------------------------