├── .editorconfig ├── .gitignore ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── jmh └── kotlin │ └── example │ └── Sequence.kt ├── main ├── java │ └── function │ │ ├── Filter.java │ │ ├── Lec16Java.java │ │ └── StringFilter.java └── kotlin │ ├── delegate │ ├── DelegateProperty.kt │ ├── LateInit.kt │ └── Sequence.kt │ ├── dsl │ ├── DockerCompose.kt │ └── OperatorOverloading.kt │ ├── extra │ ├── Lec24.kt │ ├── Lec25.kt │ ├── Lec26.kt │ └── abc │ │ └── d │ │ └── A.kt │ ├── function │ ├── Lec13.kt │ ├── Lec14.kt │ ├── Lec15.kt │ └── Lec16.kt │ ├── generic │ ├── Animal.kt │ ├── Cage.kt │ ├── Cage2.kt │ ├── Cage3.kt │ ├── Cage5.kt │ └── TypeErase.kt │ └── reflection │ ├── Annotation.kt │ ├── DI.kt │ ├── Reflection.kt │ └── TypeToken.kt └── test └── kotlin └── delegate └── PersonTest.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_size = 2 5 | indent_style = space 6 | 7 | tab_width = 2 8 | end_of_line = lf 9 | charset = utf-8 10 | trim_trailing_whitespace = true 11 | insert_final_newline = true 12 | 13 | [*.{kt, kts}] 14 | kotlin_code_style = ktlint_official 15 | ktlint_standard_no-blank-line-before-rbrace = false 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | build/ 3 | .gradle/ 4 | .java-version 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 코틀린 고급편 2 | 3 | 강의 링크 : https://inf.run/hVvN 4 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 2 | 3 | plugins { 4 | kotlin("jvm") version "1.8.10" 5 | id("me.champeau.gradle.jmh") version "0.5.3" 6 | id("org.jetbrains.dokka") version "1.8.10" 7 | id("org.jlleitschuh.gradle.ktlint") version "11.4.2" 8 | } 9 | 10 | group = "org.example" 11 | version = "1.0-SNAPSHOT" 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation("org.reflections:reflections:0.10.2") 19 | implementation("org.jetbrains.kotlin:kotlin-reflect:1.8.10") 20 | testImplementation(kotlin("test")) 21 | testImplementation("org.assertj:assertj-core:3.24.2") 22 | } 23 | 24 | tasks.test { 25 | useJUnitPlatform() 26 | } 27 | 28 | tasks.withType { 29 | kotlinOptions.jvmTarget = "11" 30 | } 31 | 32 | jmh { 33 | threads = 1 34 | fork = 1 35 | warmupIterations = 1 36 | iterations = 1 37 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lannstark/advanced-kotlin/39f7aaf830428b8c9b9b852bf65dd697536b2d6f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "kotlin" 3 | 4 | -------------------------------------------------------------------------------- /src/jmh/kotlin/example/Sequence.kt: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import org.openjdk.jmh.annotations.Benchmark 4 | import org.openjdk.jmh.annotations.BenchmarkMode 5 | import org.openjdk.jmh.annotations.Mode 6 | import org.openjdk.jmh.annotations.OutputTimeUnit 7 | import org.openjdk.jmh.annotations.Scope 8 | import org.openjdk.jmh.annotations.Setup 9 | import org.openjdk.jmh.annotations.State 10 | import java.util.concurrent.TimeUnit 11 | import kotlin.random.Random 12 | import kotlin.system.measureTimeMillis 13 | 14 | @State(Scope.Benchmark) 15 | @BenchmarkMode(Mode.AverageTime) 16 | @OutputTimeUnit(TimeUnit.MICROSECONDS) 17 | open class SequenceTest { 18 | private val fruits = mutableListOf() 19 | 20 | @Setup 21 | fun init() { 22 | (1..2_000_000).forEach { _ -> fruits.add(Fruit.random()) } 23 | } 24 | 25 | @Benchmark 26 | fun kotlinSequence() { 27 | val avg = fruits.asSequence() 28 | .filter { it.name == "사과" } 29 | .map { it.price } 30 | .take(10_000) 31 | .average() 32 | } 33 | 34 | @Benchmark 35 | fun kotlinIterator() { 36 | val time = measureTimeMillis { 37 | val avg = fruits 38 | .filter { it.name == "사과" } 39 | .map { it.price } 40 | .take(10_000) 41 | .average() 42 | } 43 | println("소요 시간 : ${time}ms") 44 | } 45 | } 46 | 47 | data class Fruit( 48 | val name: String, 49 | val price: Long, // 1,000원부터 20,000원 사이 50 | ) { 51 | companion object { 52 | private val NAME_CANDIDATES = listOf("사과", "바나나", "수박", "채리", "오렌지") 53 | fun random(): Fruit { 54 | val randNum1 = Random.nextInt(0, 5) 55 | val randNum2 = Random.nextLong(1000, 20001) 56 | return Fruit( 57 | name = NAME_CANDIDATES[randNum1], 58 | price = randNum2 59 | ) 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/function/Filter.java: -------------------------------------------------------------------------------- 1 | package function; 2 | 3 | public interface Filter { 4 | abstract public boolean predicate(T t); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/function/Lec16Java.java: -------------------------------------------------------------------------------- 1 | package function; 2 | 3 | public class Lec16Java { 4 | public static void main(String[] args) { 5 | StringFilter filter = s -> s.startsWith("A"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/function/StringFilter.java: -------------------------------------------------------------------------------- 1 | package function; 2 | 3 | public interface StringFilter { 4 | abstract public boolean predicate(String str); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/kotlin/delegate/DelegateProperty.kt: -------------------------------------------------------------------------------- 1 | package delegate 2 | 3 | import kotlin.properties.Delegates 4 | import kotlin.properties.PropertyDelegateProvider 5 | import kotlin.properties.ReadOnlyProperty 6 | import kotlin.reflect.KProperty 7 | 8 | class Person3 { 9 | val name: String by LazyInitProperty { 10 | Thread.sleep(2_000) 11 | "김수한무" 12 | } 13 | 14 | val status: String by object : ReadOnlyProperty { 15 | private var isGreen: Boolean = false 16 | override fun getValue(thisRef: Person3, property: KProperty<*>): String { 17 | return if (isGreen) { 18 | isGreen = false 19 | "Happy" 20 | } else { 21 | isGreen = true 22 | "Sad" 23 | } 24 | } 25 | } 26 | } 27 | 28 | class LazyInitProperty(val init: () -> T): ReadOnlyProperty { 29 | private var _value: T? = null 30 | private val value: T 31 | get() { 32 | if (_value == null) { 33 | this._value = init() 34 | } 35 | return _value!! 36 | } 37 | 38 | override fun getValue(thisRef: Any, property: KProperty<*>): T { 39 | return value 40 | } 41 | } 42 | 43 | class Person4 { 44 | var age: Int by Delegates.observable(20) { _, oldValue, newValue -> 45 | println("이전 값 : ${oldValue} 새로운 값 : ${newValue}") 46 | } 47 | } 48 | 49 | fun main() { 50 | Person5() 51 | } 52 | 53 | class Person5 { 54 | val name by DelegateProvider("최태현") 55 | val country by DelegateProvider("한국") 56 | } 57 | 58 | class DelegateProvider( 59 | private val initValue: String 60 | ) : PropertyDelegateProvider { 61 | override fun provideDelegate(thisRef: Any, property: KProperty<*>): DelegateProperty { 62 | if (property.name != "name") { 63 | throw IllegalArgumentException("${property.name}은 안되요! name만 연결 가능합니다!") 64 | } 65 | return DelegateProperty(initValue) 66 | } 67 | } 68 | 69 | class DelegateProperty( 70 | private val initValue: String, 71 | ) : ReadOnlyProperty { 72 | override fun getValue(thisRef: Any, property: KProperty<*>): String { 73 | return initValue 74 | } 75 | } 76 | 77 | 78 | interface Fruit { 79 | val name: String 80 | val color: String 81 | fun bite() 82 | } 83 | 84 | open class Apple : Fruit { 85 | override val name: String 86 | get() = "사과" 87 | override val color: String 88 | get() = "빨간색" 89 | override fun bite() { 90 | print("사과 톡톡~ 아삭~") 91 | } 92 | } 93 | 94 | class GreenApple : Fruit { 95 | override val name: String 96 | get() = "사과" 97 | override val color: String 98 | get() = "초록색" 99 | 100 | override fun bite() { 101 | print("사과 톡톡~ 아삭~") 102 | } 103 | } 104 | 105 | class GreenApple2 : Apple() { 106 | override val color: String 107 | get() = "초록색" 108 | } 109 | 110 | class GreenApple3( 111 | private val apple: Apple 112 | ) : Fruit by apple { 113 | override val color: String 114 | get() = "초록색" 115 | } -------------------------------------------------------------------------------- /src/main/kotlin/delegate/LateInit.kt: -------------------------------------------------------------------------------- 1 | package delegate 2 | 3 | class Person { 4 | lateinit var name: String 5 | 6 | val isKim: Boolean 7 | get() = this.name.startsWith("김") 8 | 9 | val maskingName: String 10 | get() = name[0] + (1 until name.length).joinToString("") { "*" } 11 | } 12 | 13 | fun main() { 14 | val p = Person() 15 | p.isKim 16 | } 17 | 18 | class Person2 { 19 | val name: String by lazy { 20 | Thread.sleep(2_000L) 21 | "김수한무" 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/kotlin/delegate/Sequence.kt: -------------------------------------------------------------------------------- 1 | package delegate 2 | 3 | fun main() { 4 | val fruits = listOf( 5 | MyFruit("사과", 1000L), 6 | MyFruit("바나나", 3000L), 7 | ) 8 | 9 | // 2,000,000 -> 모두 필터링! 10 | // [과일, 과일 과일, .. ] 11 | val avg = fruits.asSequence() 12 | .filter { it.name == "사과" } 13 | .map { it.price } 14 | .take(10_000) 15 | .average() 16 | } 17 | 18 | data class MyFruit( 19 | val name: String, 20 | val price: Long, // 1,000원부터 20,000원 사이 21 | ) 22 | -------------------------------------------------------------------------------- /src/main/kotlin/dsl/DockerCompose.kt: -------------------------------------------------------------------------------- 1 | package dsl 2 | 3 | import kotlin.properties.ReadWriteProperty 4 | import kotlin.reflect.KProperty 5 | 6 | fun main() { 7 | val yml = dockerCompose { 8 | version { 3 } 9 | service(name = "db") { 10 | image { "mysql" } 11 | env("USER" - "myuser") 12 | env("PASSWORD" - "mypassword") 13 | port(host = 9999, container = 3306) 14 | } 15 | } 16 | 17 | val yml2 = dockerCompose { 18 | service("") { 19 | // service("") { // @DslMarker 효과 20 | // 21 | // } 22 | } 23 | } 24 | 25 | println(yml.render(" ")) 26 | } 27 | 28 | fun dockerCompose(init: DockerCompose.() -> Unit): DockerCompose { 29 | val dockerCompose = DockerCompose() 30 | dockerCompose.init() 31 | return dockerCompose 32 | } 33 | 34 | @YamlDsl 35 | class DockerCompose { 36 | private var version: Int by onceNotNull() 37 | private val services = mutableListOf() 38 | 39 | fun version(init: () -> Int) { 40 | version = init() 41 | } 42 | 43 | fun service(name: String, init: Service.() -> Unit) { 44 | val service = Service(name) 45 | service.init() 46 | services.add(service) 47 | } 48 | 49 | fun render(indent: String): String { 50 | val builder = StringBuilder() 51 | builder.appendNew("version: '$version'") 52 | builder.appendNew("services:") 53 | builder.appendNew(services.joinToString("\n") { it.render(indent) }.addIndent(indent, 1)) 54 | return builder.toString() 55 | } 56 | } 57 | 58 | @YamlDsl 59 | class Service(private val name: String) { 60 | private var image: String by onceNotNull() 61 | private val environments = mutableListOf() 62 | private val portRules = mutableListOf() 63 | 64 | fun image(init: () -> String) { 65 | image = init() 66 | } 67 | 68 | fun env(environment: Environment) { 69 | this.environments.add(environment) 70 | } 71 | 72 | fun port(host: Int, container: Int) { 73 | this.portRules.add(PortRule(host = host, container = container)) 74 | } 75 | 76 | fun render(indent: String): String { 77 | val builder = StringBuilder() 78 | builder.appendNew("$name:") 79 | builder.appendNew("image: $image", indent, 1) 80 | builder.appendNew("environment:") 81 | environments.joinToString("\n") { "- ${it.key}: ${it.value}" } 82 | .addIndent(indent, 1) 83 | .also { builder.appendNew(it) } 84 | builder.appendNew("port:") 85 | portRules.joinToString("\n") { "- \"${it.host}:${it.container}\"" } 86 | .addIndent(indent, 1) 87 | .also { builder.appendNew(it) } 88 | return builder.toString() 89 | } 90 | } 91 | 92 | data class Environment( 93 | val key: String, 94 | val value: String, 95 | ) 96 | 97 | operator fun String.minus(other: String): Environment { 98 | return Environment( 99 | key = this, 100 | value = other, 101 | ) 102 | } 103 | 104 | data class PortRule( 105 | val host: Int, 106 | val container: Int 107 | ) 108 | 109 | fun onceNotNull() = object : ReadWriteProperty { 110 | private var value: T? = null 111 | override fun getValue(thisRef: Any?, property: KProperty<*>): T { 112 | if (this.value == null) { 113 | throw IllegalArgumentException("변수가 초기화되지 않았습니다") 114 | } 115 | return this.value!! 116 | } 117 | 118 | override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { 119 | if (this.value != null) { 120 | throw IllegalArgumentException("이 변수는 한 번만 값을 초기화할 수 있습니다.") 121 | } 122 | this.value = value 123 | } 124 | } 125 | 126 | fun StringBuilder.appendNew(str: String, indent: String = "", times: Int = 0) { 127 | (1..times).forEach { _ -> this.append(indent) } 128 | this.append(str) 129 | this.append("\n") 130 | } 131 | 132 | fun String.addIndent(indent: String, times: Int = 0): String { 133 | val allIndent = (1..times).joinToString("") { indent } 134 | return this.split("\n") 135 | .joinToString("\n") { "$allIndent$it" } 136 | } 137 | 138 | @DslMarker 139 | annotation class YamlDsl -------------------------------------------------------------------------------- /src/main/kotlin/dsl/OperatorOverloading.kt: -------------------------------------------------------------------------------- 1 | package dsl 2 | 3 | import java.time.LocalDate 4 | 5 | class OperatorOverloading { 6 | } 7 | 8 | data class Point( 9 | val x: Int, 10 | val y: Int, 11 | ) { 12 | operator fun unaryMinus(): Point { 13 | return Point(-x, -y) 14 | } 15 | 16 | operator fun unaryPlus(): Int { 17 | return x 18 | } 19 | 20 | operator fun inc(): Point { 21 | return Point(x + 1, y + 1) 22 | } 23 | } 24 | 25 | fun main() { 26 | var point = Point(20, -10) 27 | println(-point) 28 | println(++point) 29 | 30 | val list = listOf("A", "B", "C") 31 | list[2] 32 | val map = mutableMapOf(1 to "A") 33 | map[2] = "B" 34 | 35 | // 2023-01-04 36 | LocalDate.of(2023, 1, 1).plusDays(3) 37 | 38 | // 2023-01-04 39 | // 2023-12-29 <- 조금 문제가 있다~~ 40 | LocalDate.of(2023, 1, 1) + Days(3) 41 | 42 | LocalDate.of(2023, 1, 1) + 3.d 43 | } 44 | 45 | data class Days(val day: Long) 46 | 47 | val Int.d: Days 48 | get() = Days(this.toLong()) 49 | 50 | operator fun LocalDate.plus(days: Days): LocalDate { 51 | return this.plusDays(days.day) 52 | } 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/kotlin/extra/Lec24.kt: -------------------------------------------------------------------------------- 1 | package extra 2 | 3 | import kotlin.system.measureTimeMillis 4 | 5 | class Lec24 { 6 | } 7 | 8 | fun main() { 9 | val result: Result = runCatching { 1 / 0 } 10 | } 11 | 12 | fun acceptOnlyTwo(num: Int) { 13 | require(num == 2) { "2만 허용!" } 14 | 15 | } 16 | 17 | class Person { 18 | val status: PersonStatus = PersonStatus.PLAYING 19 | 20 | fun sleep() { 21 | check(this.status == PersonStatus.PLAYING) { "에러 메시지!" } 22 | } 23 | 24 | enum class PersonStatus { 25 | PLAYING, SLEEPING 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/kotlin/extra/Lec25.kt: -------------------------------------------------------------------------------- 1 | package extra 2 | 3 | import kotlin.reflect.KClass 4 | 5 | class Lec25 { 6 | } 7 | 8 | tailrec fun factorialV2(n: Int, curr: Int = 1): Int { 9 | return if (n <= 1) { 10 | curr 11 | } else { 12 | factorialV2(n - 1, n * curr) 13 | } 14 | } 15 | 16 | 17 | @JvmInline 18 | value class Key(val key: String) 19 | 20 | class User( 21 | val id: Id, 22 | val name: String, 23 | ) 24 | 25 | class Book( 26 | val id: Id, 27 | val author: String, 28 | ) 29 | 30 | fun handle(userId: Long, bookId: Long) { 31 | 32 | } 33 | 34 | fun handleV2(userId: Id, bookId: Id) { 35 | 36 | } 37 | 38 | @JvmInline 39 | value class Id(val id: Long) 40 | 41 | @JvmInline 42 | value class Number(val num: Long) { 43 | init { 44 | require(num in 1..10) 45 | } 46 | } 47 | 48 | 49 | fun logic(n: Int) { 50 | when { 51 | n > 0 -> throw AException() 52 | n == 0 -> throw BException() 53 | } 54 | throw CException() 55 | } 56 | 57 | class AException : RuntimeException() 58 | class BException : RuntimeException() 59 | class CException : RuntimeException() 60 | 61 | fun main() { 62 | try { 63 | logic(10) 64 | } catch(e: Exception) { 65 | when (e) { 66 | is AException, 67 | is BException -> TODO() 68 | is CException -> TODO() 69 | } 70 | throw e 71 | } 72 | 73 | runCatching { logic(10) } 74 | .onError(AException::class, BException::class) { 75 | println("A 또는 B 예외가 발생했습니다.") 76 | } 77 | .onError(AException::class) { 78 | 79 | } 80 | 81 | 82 | // val key = Key("비밀 번호") 83 | // println(key) 84 | // 85 | // val userId = 1L 86 | // val bookId = 2L 87 | // handle( 88 | // bookId = bookId, 89 | // userId = userId, 90 | // ) 91 | // 92 | // val inlineUserId = Id(1L) 93 | // val inlineBookId = Id(2L) 94 | // handleV2(inlineUserId, inlineBookId) 95 | } 96 | 97 | class ResultWrapper( 98 | private val result: Result, 99 | private val knownExceptions: MutableList>, 100 | ) { 101 | fun toResult(): Result { 102 | return this.result 103 | } 104 | 105 | fun onError(vararg exceptions: KClass, action: (Throwable) -> Unit): ResultWrapper { 106 | this.result.exceptionOrNull()?.let { 107 | if (it::class in exceptions && it::class !in this.knownExceptions) { 108 | action(it) 109 | } 110 | } 111 | return this 112 | } 113 | 114 | } 115 | 116 | fun Result.onError(vararg exceptions: KClass, action: (Throwable) -> Unit): ResultWrapper { 117 | exceptionOrNull()?.let { 118 | if (it::class in exceptions) { 119 | action(it) 120 | } 121 | } 122 | return ResultWrapper(this, exceptions.toMutableList()) 123 | } -------------------------------------------------------------------------------- /src/main/kotlin/extra/Lec26.kt: -------------------------------------------------------------------------------- 1 | package extra 2 | 3 | class Lec26 { 4 | } 5 | 6 | // kdoc 7 | /** 8 | * 박스를 나타내는 클래스. 9 | * 10 | * **강조** 11 | * - A 12 | * - B 13 | * - C 14 | * 15 | * @param T 박스의 아이템 타입 16 | * @property name 박스의 이름 17 | * @sample extra.abc.d.helloWorld 18 | */ 19 | class Box(val name: String) { 20 | 21 | /** 22 | * @param item 박스에 들어갈 아이템 23 | */ 24 | fun add(item: T): Boolean { 25 | TODO() 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/kotlin/extra/abc/d/A.kt: -------------------------------------------------------------------------------- 1 | package extra.abc.d 2 | 3 | fun helloWorld() { 4 | println("Hello World") 5 | } -------------------------------------------------------------------------------- /src/main/kotlin/function/Lec13.kt: -------------------------------------------------------------------------------- 1 | package function 2 | 3 | 4 | class Lec13 { 5 | 6 | } 7 | 8 | fun main() { 9 | // 람다식 10 | // compute(5, 3) { a, b -> a + b } 11 | 12 | // 익명함수 13 | // compute(5, 3, fun(a, b) = a + b) 14 | 15 | iterate(listOf(1, 2, 3, 4, 5)) { num -> 16 | if (num != 3) { 17 | println(num) 18 | } 19 | } 20 | 21 | println("ABC") 22 | } 23 | 24 | 25 | //fun iterate(numbers: List, exec: (Int) -> Unit) { 26 | // for (number in numbers) { 27 | // exec(number) 28 | // } 29 | //} 30 | 31 | fun calculate(num1: Int, num2: Int, oper: Operator): Int = oper(num1, num2) 32 | 33 | enum class Operator( 34 | private val oper: Char, 35 | private val calcFun: (Int, Int) -> Int, 36 | ) { 37 | PLUS('+', { a, b -> a + b }), 38 | MINUS('-', { a, b -> a - b }), 39 | MULTIPLY('-', { a, b -> a * b }), 40 | DIVIDE('-', { a, b -> 41 | if (b == 0) { 42 | throw IllegalArgumentException("0으로 나눌 수 없습니다!") 43 | } else { 44 | a / b 45 | } 46 | }), 47 | ; 48 | 49 | operator fun invoke(num1: Int, num2: Int): Int { 50 | return this.calcFun(num1, num2) 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/main/kotlin/function/Lec14.kt: -------------------------------------------------------------------------------- 1 | package function 2 | 3 | 4 | class Lec14 { 5 | } 6 | 7 | fun main() { 8 | var num = 5 9 | num += 1 10 | val plusOne: () -> Unit = { num += 1 } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/main/kotlin/function/Lec15.kt: -------------------------------------------------------------------------------- 1 | package function 2 | 3 | class Lec15 { 4 | } 5 | 6 | fun main() { 7 | iterate(listOf(1, 2, 3, 4, 5)) { num -> 8 | if (num == 3) { 9 | // return // crossinline을 쓰면 사용을 할 수 없다. 10 | } 11 | println(num) 12 | } 13 | } 14 | 15 | inline fun iterate(numbers: List, crossinline exec: (Int) -> Unit) { 16 | for (num in numbers) { 17 | exec(num) 18 | } 19 | } 20 | 21 | inline fun repeat( 22 | times: Int, 23 | noinline exec: () -> Unit, // noinline 지시어를 붙였다! 24 | ) { 25 | for (i in 1..times) { 26 | exec() 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /src/main/kotlin/function/Lec16.kt: -------------------------------------------------------------------------------- 1 | package function 2 | 3 | fun add(a: Int, b: Int) = a + b 4 | 5 | fun main() { 6 | 7 | val add1 = { a: Int, b: Int -> a + b } 8 | 9 | val add2 = fun (a: Int, b: Int) = a + b 10 | 11 | ::add 12 | 13 | //KStringFilter { it.startsWith("A") } 14 | } 15 | 16 | fun consumeFilter(filter: StringFilter) { } 17 | 18 | fun consumeFilter(filter: Filter) {} 19 | 20 | fun interface KStringFilter { 21 | fun predicate(str: String): Boolean 22 | } -------------------------------------------------------------------------------- /src/main/kotlin/generic/Animal.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | abstract class Animal( 4 | val name: String, 5 | ) 6 | 7 | abstract class Fish(name: String) : Animal(name) 8 | 9 | // 금붕어 10 | class GoldFish(name: String) : Fish(name) 11 | 12 | // 잉어 13 | class Carp(name: String) : Fish(name) -------------------------------------------------------------------------------- /src/main/kotlin/generic/Cage.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | fun main() { 4 | val goldFishCage = Cage2() 5 | goldFishCage.put(GoldFish("금붕어")) 6 | 7 | val fishCage = Cage2() 8 | // fishCage.moveFrom(goldFishCage) // Type mismatch 9 | } 10 | 11 | class Cage { 12 | private val animals: MutableList = mutableListOf() 13 | 14 | fun getFirst(): Animal { 15 | return animals.first() 16 | } 17 | 18 | fun put(animal: Animal) { 19 | this.animals.add(animal) 20 | } 21 | 22 | fun moveFrom(cage: Cage) { 23 | this.animals.addAll(cage.animals) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/kotlin/generic/Cage2.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | fun main() { 4 | val cage: Cage2 = Cage2() 5 | } 6 | 7 | class Cage2 { 8 | private val animals: MutableList = mutableListOf() 9 | 10 | fun getFirst(): T { 11 | return animals.first() 12 | } 13 | 14 | fun put(animal: T) { 15 | this.animals.add(animal) 16 | } 17 | 18 | fun moveFrom(otherCage: Cage2) { 19 | this.animals.addAll(otherCage.animals) 20 | } 21 | 22 | fun moveTo(otherCage: Cage2) { 23 | otherCage.animals.addAll(this.animals) 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/kotlin/generic/Cage3.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | fun main() { 4 | val fishCage = Cage3() 5 | val animalCage: Cage3 = fishCage 6 | } 7 | 8 | class Cage3 { 9 | private val animals: MutableList = mutableListOf() 10 | 11 | fun getFirst(): T { 12 | return this.animals.first() 13 | } 14 | 15 | fun getAll(): List { 16 | return this.animals 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/generic/Cage5.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | fun main() { 4 | 5 | } 6 | 7 | abstract class Bird( 8 | name: String, 9 | private val size: Int, 10 | ) : Animal(name), Comparable { 11 | override fun compareTo(other: Bird): Int { 12 | return this.size.compareTo(other.size) 13 | } 14 | } 15 | 16 | class Sparrow : Bird("참새", 100) 17 | class Eagle : Bird("독수리", 500) 18 | 19 | 20 | class Cage5( 21 | private val animals: MutableList = mutableListOf(), 22 | ) where T : Animal, T : Comparable { 23 | 24 | fun printAfterSorting() { 25 | this.animals.sorted() 26 | .map { it.name } 27 | .let { println(it) } 28 | } 29 | 30 | fun getFirst(): T { 31 | return animals.first() 32 | } 33 | 34 | fun put(animal: T) { 35 | this.animals.add(animal) 36 | } 37 | 38 | fun moveFrom(otherCage: Cage5) { 39 | this.animals.addAll(otherCage.animals) 40 | } 41 | 42 | fun moveTo(otherCage: Cage5) { 43 | otherCage.animals.addAll(this.animals) 44 | } 45 | } 46 | 47 | fun List.hasIntersection(other: List): Boolean { 48 | return (this.toSet() intersect other.toSet()).isNotEmpty() 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/main/kotlin/generic/TypeErase.kt: -------------------------------------------------------------------------------- 1 | package generic 2 | 3 | inline fun T.toSuperString() { 4 | println("${T::class.java.name}: $this") 5 | } 6 | 7 | inline fun List<*>.hasAnyInstanceOf(): Boolean { 8 | return this.any { it is T } 9 | } 10 | 11 | class TypeErase { 12 | } 13 | 14 | class CageShadow { 15 | fun addAnimal(animal: T) { 16 | 17 | } 18 | } 19 | 20 | 21 | fun main() { 22 | val cage = CageShadow() 23 | cage.addAnimal(GoldFish("금붕어")) 24 | cage.addAnimal(Carp("잉어")) 25 | } 26 | 27 | open class CageV1 { 28 | open fun addAnimal(animal: T) { 29 | 30 | } 31 | } 32 | 33 | class CageV2 : CageV1() { 34 | override fun addAnimal(animal: T) { 35 | super.addAnimal(animal) 36 | } 37 | } 38 | 39 | class GoldFishCageV2 : CageV1() { 40 | override fun addAnimal(animal: GoldFish) { 41 | super.addAnimal(animal) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/kotlin/reflection/Annotation.kt: -------------------------------------------------------------------------------- 1 | package reflection 2 | 3 | import kotlin.reflect.KClass 4 | 5 | @Repeatable 6 | @Target(AnnotationTarget.CLASS) 7 | annotation class Shape( 8 | val texts: Array 9 | ) 10 | 11 | @Shape(["C"]) 12 | @Shape(["A", "B"]) 13 | class Annotation { 14 | } 15 | 16 | fun main() { 17 | val clazz: KClass = Annotation::class 18 | } -------------------------------------------------------------------------------- /src/main/kotlin/reflection/DI.kt: -------------------------------------------------------------------------------- 1 | package reflection 2 | 3 | import org.reflections.Reflections 4 | import kotlin.reflect.KClass 5 | import kotlin.reflect.KFunction 6 | import kotlin.reflect.KParameter 7 | import kotlin.reflect.cast 8 | 9 | class DI 10 | 11 | object ContainerV1 { 12 | // 등록한 클래스 보관! = KClass를 보관! 13 | private val registeredClasses = mutableSetOf>() 14 | 15 | fun register(clazz: KClass<*>) { 16 | registeredClasses.add(clazz) 17 | } 18 | 19 | fun getInstance(type: KClass): T { 20 | return registeredClasses.firstOrNull { clazz -> clazz == type } 21 | ?.let { clazz -> clazz.constructors.first().call() as T } 22 | ?: throw IllegalArgumentException("해당 인스턴스 타입을 찾을 수 없습니다") 23 | } 24 | } 25 | 26 | fun start(clazz: KClass<*>) { 27 | val reflections = Reflections(clazz.packageName) 28 | val jClasses = reflections.getTypesAnnotatedWith(MyClass::class.java) 29 | jClasses.forEach { jClass -> ContainerV2.register(jClass.kotlin) } 30 | } 31 | 32 | private val KClass<*>.packageName: String 33 | get() { 34 | val qualifiedName = this.qualifiedName 35 | ?: throw IllegalArgumentException("익명 객체입니다!") 36 | val hierarchy = qualifiedName.split(".") 37 | return hierarchy.subList(0, hierarchy.lastIndex).joinToString(".") 38 | } 39 | 40 | object ContainerV2 { 41 | // 등록한 클래스 보관! = KClass를 보관! 42 | private val registeredClasses = mutableSetOf>() 43 | private val cachedInstances = mutableMapOf, Any>() 44 | 45 | fun register(clazz: KClass<*>) { 46 | registeredClasses.add(clazz) 47 | } 48 | 49 | fun getInstance(type: KClass): T { 50 | if (type in cachedInstances) { 51 | return type.cast(cachedInstances[type]) 52 | } 53 | 54 | val instance = registeredClasses.firstOrNull { clazz -> clazz == type } 55 | ?.let { clazz -> instantiate(clazz) as T } 56 | ?: throw IllegalArgumentException("해당 인스턴스 타입을 찾을 수 없습니다") 57 | cachedInstances[type] = instance 58 | return instance 59 | } 60 | 61 | private fun instantiate(clazz: KClass): T { 62 | val constructor = findUsableConstructor(clazz) 63 | val params = constructor.parameters 64 | .map { param -> getInstance(param.type.classifier as KClass<*>) } 65 | .toTypedArray() 66 | return constructor.call(*params) 67 | } 68 | 69 | // clazz의 consturcotr들 중, 사용할 수 있는 constructor 70 | // consturctor에 넣어야 하는 타입들이 모두 등록된 경우 (컨테이너에서 관리하고 있는 경우) 71 | private fun findUsableConstructor(clazz: KClass): KFunction { 72 | return clazz.constructors 73 | .firstOrNull { constructor -> constructor.parameters.isAllRegistered } 74 | ?: throw IllegalArgumentException("사용할 수 있는 생성자가 없습니다") 75 | } 76 | 77 | private val List.isAllRegistered: Boolean 78 | get() = this.all { it.type.classifier in registeredClasses } 79 | } 80 | 81 | 82 | fun main() { 83 | // ContainerV1.register(AService::class) 84 | // val aService = ContainerV1.getInstance(AService::class) 85 | // aService.print() 86 | 87 | // ContainerV2.register(AService::class) 88 | // ContainerV2.register(BService::class) 89 | // 90 | // val bService = ContainerV2.getInstance(BService::class) 91 | // bService.print() 92 | 93 | start(DI::class) 94 | val bService = ContainerV2.getInstance(BService::class) 95 | bService.print() 96 | } 97 | 98 | annotation class MyClass 99 | 100 | @MyClass 101 | class AService() { 102 | fun print() { 103 | println("A Service 입니다") 104 | } 105 | } 106 | 107 | class CService 108 | 109 | @MyClass 110 | class BService( 111 | private val aService: AService, 112 | private val cService: CService?, 113 | ) { 114 | 115 | constructor(aService: AService): this(aService, null) 116 | 117 | fun print() { 118 | this.aService.print() 119 | } 120 | } -------------------------------------------------------------------------------- /src/main/kotlin/reflection/Reflection.kt: -------------------------------------------------------------------------------- 1 | package reflection 2 | 3 | import kotlin.reflect.KClass 4 | import kotlin.reflect.KFunction 5 | import kotlin.reflect.KType 6 | import kotlin.reflect.cast 7 | import kotlin.reflect.full.createInstance 8 | import kotlin.reflect.full.createType 9 | import kotlin.reflect.full.hasAnnotation 10 | 11 | 12 | @Target(AnnotationTarget.CLASS) 13 | annotation class Executable 14 | 15 | @Executable 16 | class Reflection { 17 | fun a() { 18 | println("A입니다") 19 | } 20 | 21 | fun b(n: Int) { 22 | println("B입니다") 23 | } 24 | } 25 | 26 | 27 | fun executeAll(obj: Any) { 28 | val kClass = obj::class 29 | if (!kClass.hasAnnotation()) { 30 | return 31 | } 32 | 33 | val callableFunctions = kClass.members.filterIsInstance>() 34 | .filter { it.returnType == Unit::class.createType() } 35 | .filter { it.parameters.size == 1 && it.parameters[0].type == kClass.createType() } 36 | 37 | callableFunctions.forEach { function -> 38 | function.call(obj) 39 | } 40 | } 41 | 42 | fun add(a: Int, b: Int) = a + b 43 | 44 | // JVM 45 | fun main() { 46 | executeAll(Reflection()) 47 | 48 | val kClass: KClass = Reflection::class 49 | 50 | val ref = Reflection() 51 | val kClass2: KClass = ref::class 52 | 53 | val kClass3: KClass = Class.forName("reflection.Reflection").kotlin 54 | kClass.java // Class 55 | kClass.java.kotlin // KClass 56 | 57 | } 58 | 59 | -------------------------------------------------------------------------------- /src/main/kotlin/reflection/TypeToken.kt: -------------------------------------------------------------------------------- 1 | package reflection 2 | 3 | import generic.* 4 | import kotlin.reflect.KClass 5 | import kotlin.reflect.KType 6 | import kotlin.reflect.cast 7 | 8 | fun main() { 9 | // val cage = Cage() 10 | // cage.put(Carp("잉어")) 11 | // cage.getFirst() as Carp // 위험! 12 | // 13 | // val typeSafeCage = TypeSafeCage() 14 | // typeSafeCage.putOne(Carp("잉어")) 15 | // val one = typeSafeCage.getOne() 16 | 17 | val superTypeToken1 = object : SuperTypeToken>() {} 18 | val superTypeToken2 = object : SuperTypeToken>() {} 19 | val superTypeToken3 = object : SuperTypeToken>() {} 20 | // println(superTypeToken2.equals(superTypeToken1)) 21 | // println(superTypeToken3.equals(superTypeToken1)) 22 | 23 | val superTypeSafeCage = SuperTypeSafeCage() 24 | superTypeSafeCage.putOne(superTypeToken2, listOf(GoldFish("금붕어1"), GoldFish("금붕어2"))) 25 | val result = superTypeSafeCage.getOne(superTypeToken2) 26 | println(result) 27 | } 28 | 29 | class TypeSafeCage { 30 | private val animals: MutableMap, Animal> = mutableMapOf() 31 | 32 | fun getOne(type: KClass): T { 33 | return type.cast(animals[type]) 34 | } 35 | 36 | fun putOne(type: KClass, animal: T) { 37 | animals[type] = type.cast(animal) 38 | } 39 | 40 | inline fun getOne(): T { 41 | return this.getOne(T::class) 42 | } 43 | 44 | inline fun putOne(animal: T) { 45 | this.putOne(T::class, animal) 46 | } 47 | } 48 | 49 | class SuperTypeSafeCage { 50 | private val animals: MutableMap, Any> = mutableMapOf() 51 | 52 | fun getOne(token: SuperTypeToken): T { 53 | return this.animals[token] as T 54 | } 55 | 56 | fun putOne(token: SuperTypeToken, animal: T) { 57 | animals[token] = animal 58 | } 59 | } 60 | 61 | 62 | // SuperTypeToken을 구현한 클래스가 인스턴스화 되자마자 63 | // T 정보를 내부 변수에 저장해버린다. 64 | // T <- List 65 | abstract class SuperTypeToken { 66 | val type: KType = this::class.supertypes[0].arguments[0].type!! 67 | 68 | override fun equals(other: Any?): Boolean { 69 | if (this === other) return true 70 | 71 | other as SuperTypeToken<*> 72 | if (type != other.type) return false 73 | return true 74 | } 75 | 76 | override fun hashCode(): Int { 77 | return type.hashCode() 78 | } 79 | } 80 | 81 | -------------------------------------------------------------------------------- /src/test/kotlin/delegate/PersonTest.kt: -------------------------------------------------------------------------------- 1 | package delegate 2 | 3 | import org.assertj.core.api.AssertionsForInterfaceTypes.assertThat 4 | import org.junit.jupiter.api.Test 5 | 6 | class PersonTest1 { 7 | private val person = Person() 8 | @Test 9 | fun isKimTest() { 10 | // given 11 | val person = person.apply { name = "김수한무" } 12 | 13 | // when & then 14 | assertThat(person.isKim).isTrue 15 | } 16 | 17 | @Test 18 | fun maskingNameTest() { 19 | // given 20 | val person = person.apply { name = "최태현" } 21 | 22 | // when & then 23 | assertThat(person.maskingName).isEqualTo("최**") 24 | } 25 | } --------------------------------------------------------------------------------