الدالة slice()‎ في Kotlin

من موسوعة حسوب
اذهب إلى التنقل اذهب إلى البحث

تقطع الدالة slice()‎ جزءًا محدَّدًا من المصفوفة أو القائمة التي استُدعيت معها ثمَّ تعيده في قائمة.

البنية العامة

يمكن تمرير مجال محدَّد إلى الدالة slice()‎ كوسيط:

fun <T> Array<out T>.slice(indices: IntRange): List<T> 
fun ByteArray.slice(indices: IntRange): List<Byte> 
fun ShortArray.slice(indices: IntRange): List<Short> 
fun IntArray.slice(indices: IntRange): List<Int> 
fun LongArray.slice(indices: IntRange): List<Long> 
fun FloatArray.slice(indices: IntRange): List<Float>
fun DoubleArray.slice(indices: IntRange): List<Double> 
fun BooleanArray.slice(indices: IntRange): List<Boolean> 
fun CharArray.slice(indices: IntRange): List<Char> 
fun <T> List<T>.slice(indices: IntRange): List<T>

أو يمكن تمرير كائن من النوع Iterable إلى الدالة slice()‎ كوسيط:

fun <T> Array<out T>.slice(indices: Iterable<Int>): List<T> 
fun ByteArray.slice(indices: Iterable<Int>): List<Byte> 
fun ShortArray.slice(indices: Iterable<Int>): List<Short> 
fun IntArray.slice(indices: Iterable<Int>): List<Int> 
fun LongArray.slice(indices: Iterable<Int>): List<Long> 
fun FloatArray.slice(indices: Iterable<Int>): List<Float> 
fun DoubleArray.slice(indices: Iterable<Int>): List<Double> 
fun BooleanArray.slice(indices: Iterable<Int>): List<Boolean> 
fun CharArray.slice(indices: Iterable<Int>): List<Char> 
fun <T> List<T>.slice(indices: Iterable<Int>): List<T>

المعاملات

indices

مجال من النوع IntRange أو كائن من النوع Iterable يحدد الجزء المراد اقتطاعه من المصفوفة أو القائمة المعطاة.

القيم المعادة

تُعاد قائمة تحوي جزءًا من المصفوفة أو القائمة المعطاة يحدِّده الوسيط indices المعطى.

أمثلة

استعمال الدالة ()slice لجلب جزء من مصفوفة يقع بين العنصر الثاني والخامس:

fun main(args: Array<String>) {
    val array = arrayOf(1, 2, 3, 4, 5, 6)

    print (array.slice(1..4)) // [2, 3, 4, 5]
}

انظر أيضًا

  • الدالة sliceArray()‎ : تقطع جزءًا محدَّدًا من المصفوفة التي استُدعيت معها ثمَّ تعيده في مصفوفة أو قائمة بحسب الوسيط الممرر إليها.
  • التابع Array.get()‎: تجلب قيمة العنصر في المصفوفة عند الفهرس المُحدَّد.
  • الدالة indexOf()‎: تجلب فهرس أول ظهور لعنصر محدَّد من المصفوفة أو المجموعة أو القائمة التي استُدعيت معها.
  • الخاصية ‎‎indices: تجلب الفهارس الصحيحة (valid indices) للمصفوفة أو المجموعة (collection).

مصادر