Skip to content

Instantly share code, notes, and snippets.

@Takhion
Last active April 3, 2019 17:36
Show Gist options
  • Save Takhion/22d0db2242af4e3fd64fa90dfa2add48 to your computer and use it in GitHub Desktop.
Save Takhion/22d0db2242af4e3fd64fa90dfa2add48 to your computer and use it in GitHub Desktop.
Kotlin generics are 🍌🍌🍌
// ...stuff...
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf(
"-Xnew-inference",
"-Xallow-kotlin-package"
)
}
}
// from: https://github.com/JetBrains/kotlin/blob/1.3.20/libraries/stdlib/src/kotlin/internal/Annotations.kt
package kotlin.internal
/**
* Specifies that the constraint built for the type during type inference should be an equality one.
*/
@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.BINARY)
internal annotation class Exact
fun <T> Set<@Exact T>.containsExactly(vararg elements: T): Boolean = TODO()
// ^^^^^^
// MAGIC!
fun shouldCompile(bananas: Set<String>) {
bananas.containsExactly()
bananas.containsExactly("one", "two")
bananas.containsExactly<String>("one", "two")
}
fun shouldNotCompile(bananas: Set<String>) {
// e: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
bananas.containsExactly<Any?>()
// e: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
bananas.containsExactly<String?>()
// e: The integer literal does not conform to the expected type String
bananas.containsExactly(1, 2)
// e: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
bananas.containsExactly<Any?>(1, 2)
// e: Null can not be a value of a non-null type String
bananas.containsExactly("", null)
// e: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
bananas.containsExactly<String?>("", null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment