Kotlin KoansでKotlin入門 第12回:Rename on import
4743 ワード
はじめに
公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。
過去記事はこちら
- Introduction
- Classes
問題
コメントを解除してコンパイルさせます。kotlin
パッケージのRandom
をKRandom
に、javaパッケージのRandom
をJRandom
にリネームします。
修正前のコード
// import kotlin.random.Random
// import java.util.Random
fun useDifferentRandomClasses(): String {
return "Kotlin random: " +
// KRandom.nextInt(2) +
" Java random:" +
// JRandom().nextInt(2) +
"."
}
問題のポイント
クラスや関数をインポートする際、import指示文の後にas NewName
を付けることで、別の名前を指定することができます。これは、異なるライブラリにある似たような名前の2つのクラスや関数を使いたい場合に便利です。
import foo.Bar // Barはアクセス可能
import bar.Bar as bBar // bBarは'bar.Bar'を意味する
解答例
import kotlin.random.Random as KRandom
import java.util.Random as JRandom
fun useDifferentRandomClasses(): String {
return "Kotlin random: " +
KRandom.nextInt(2) +
" Java random:" +
JRandom().nextInt(2) +
"."
}
import kotlin.random.Random as KRandom
import java.util.Random as JRandom
fun useDifferentRandomClasses(): String {
return "Kotlin random: " +
KRandom.nextInt(2) +
" Java random:" +
JRandom().nextInt(2) +
"."
}
Author And Source
この問題について(Kotlin KoansでKotlin入門 第12回:Rename on import), 我々は、より多くの情報をここで見つけました https://qiita.com/kosuke1/items/f11465cc15a94e7589a3著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .