Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created August 18, 2021 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakamura-to/709e70370989101a25762d7b7ef5cbde to your computer and use it in GitHub Desktop.
Save nakamura-to/709e70370989101a25762d7b7ef5cbde to your computer and use it in GitHub Desktop.
拡張関数の利用範囲を限定する方法
fun String.globalExtension() {
println(this)
}
class Scope {
fun String.narrowExtension() {
println(this)
}
}
fun dsl(block: Scope.()-> Unit) {
block(Scope())
}
fun main() {
"どこからでも呼び出せる拡張関数".globalExtension()
dsl {
"どこからでも呼び出せる拡張関数".globalExtension()
"特定のラムダ式の中でしか呼び出せない拡張関数".narrowExtension()
}
// これはコンパイルエラー
// "特定のラムダ式の中でしか呼び出せない拡張関数".narrowExtension()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment