微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有扩展相同数据结构的多个实现的函数的类可以吗?

如何解决具有扩展相同数据结构的多个实现的函数的类可以吗?

我正在 CS 课程中学习数据结构。 大学教授给我们分配了一个项目,我们必须在不使用我们选择使用的编程语言已经提供的数据结构的情况下,实现从 0 开始的每个数据结构。

所有这些都是通过考试的实验室部分所必需的:

  • 对于每一种数据结构,我们都必须开发一种以上的已知实现。

     An istance : For the List data structure
                  We have to develop ArrayList,LinkedList and DoubleLinkedList in separate 
                  classes and packages.
    
  • 我们必须遵循已知的正式规范。

     An istance : For the List class
                  We can only declare "data structure releated" members and attributes
                  Like create,delete,head,isEmpty,isLast,next,prevIoUs,insert,write,read,remove
    

我完成了那些,但是

我需要为每个数据结构将“服务功能”放在一个单独的类/文件中,它应该适用于它们的每个类(实现)。

然后按照上面的步骤:

我必须开发一个名为“ListServices”的类/文件,它应该“扩展”每个类,例如: 数组列表 我的链表 MyDoubleLinkedList

对于服务,我的意思是数据结构的“不需要”功能,例如:

printList() //it prints the whole list

goToList(position : Int) //goes to the position using Integers

sortList(whichsort : String,order : String) //whichsort = quicksort,mergesort and order ascending/descending

purgeList() //it deletes all the "dupled" elements(or the more than 2 occurances per element)

通常我会在上面命名的每个类中定义这些:

class MyArrayList<T>{
.
.
.
fun printList(){}
}
class MyLinkedList<T>{
.
.
.
fun printList(){}
}
class MyDoubleLinkedList<T>{
.
.
.
fun printList(){}
}
import edu.uni.lists.MyArrayList as MyList //or whatever other implementation I will interchange instead of MyArrayList

fun main() {
        val l1 = MyList<String> ()
        l1.create() //init
        if(l1.isEmpty())
            println("List is empty")

        l1.insert("11",l1.head())
        l1.insert("10",l1.head())
        l1.insert("9",l1.head())
        l1.insert("8",l1.head())
        l1.insert("7",l1.head())
        l1.insert("69",l1.head())
        l1.printList() //should print the whole list

}

无论我使用什么实现,printList() 都将只使用数据结构运算符而不使用其他任何东西。 对于每个 List 实现,printList() 的代码都是相同的。 我不能在那里放置服务功能

我需要将 printlist()[和其他服务函数]从列表实现“移出”到另一个类或文件

如何使用 Kotlin 完成此请求?

谢谢大家。

附言= 我不是英语母语人士,抱歉,如果我没有如您所料那样清楚,请随时提问,我会回复

解决方法

您应该创建一个 inteface 并在您的所有类中扩展它

interface ListServices {
    fun printList()
}
class myArrayList<T> : ListServices {}
class myLinkedList<T> : ListServices {}
class myDoubleLinkedList<T> : ListServices {}

或者,如果您不想在这些类之间创建关系,可以使用 extension functions

object ListServices {
    fun <T> myArrayList<T>.printList() {}
    fun <T> myLinkedList<T>.printList() {}
    fun <T> myDoubleLinkedList<T>.printList() {}
}

T 是一个 type parameter,你必须在函数名之前声明它。如果您的 print 函数不关心这种类型,您可以使用 star-projection:

class myArrayList<T>(var foo: T)

object ListServices {
    fun myArrayList<*>.printList() {
        // here foo type is Any?
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。