Kotlin list of classes

How to initialize an array of classes in kotlin?

First of all, your code has several errors. This might be an MCVE and/or copy-paste issue, but I need to address these before I get started on the arrays.

var releve before the notes class isn’t allowed. You don’t assign it, you don’t declare a type, and the compiler will complain if you copy-paste the code from your question.

Second, the array var itself: Array is upper-case, and initialization is separate. This would be more valid (note that this still does not work — the solution for that comes later in this answer):

var releve: Array = Array(10) // or var releve = Array(10)

And the last thing before I start on the array itself: please read the language conventions, especially the naming ones. Your classes should all start with an upper-case letter.

Kotlin arrays are quite different from Java arrays in many ways, but the most notable one being that direct array initialization also requires an initializer.

The brackets are expected to create a new instance, which you don’t. You create a String, which isn’t, in your case, a modul .

There are several ways to fix this depending on how you want to do this.

If you have instances you want to add to the array, you can use arrayOf :

arrayOf(modulInstance, modulInstance2, . ) 

If you want to create them directly, you can use your approach:

A note about both of these: because of the initialization, you get automatic type inference and don’t need to explicitly declare

If you want Java-style arrays, you need an array of nulls.

There’s two ways to do this:

var releve = arrayOfNulls(10) // or var releve = Array(10)

I highly recommend the first one, because it’s cleaner. I’m not sure if there’s a difference performance-wise though.

Note that this does infer a nullable type to the array, but it lets you work with arrays in a similar way to Java. Initialization from this point is just like Java: releve[i] = modul() . This approach is mostly useful if you have arguments you want to add to each of the classes and you need to do so manually. Using the manual initializers also provides you with an index (see the documentation) which you can use while initializing.

Note that if you’re using a for loop to initialize, you can use Array(10) < YourClass() >as well, and use the supplied index if you need any index-sensitive information, such as function arguments. There’s of course nothing wrong with using a for loop, but it can be cleaner.

Источник

Define collection of data class

Defining a List collection in Kotlin in different ways:

val users: List = listOf( User("Tom", 32), User("John", 64) ) 
val users: MutableList = mutableListOf( User("Tom", 32), User("John", 64) ) 
val users = mutableListOf() //or val users = ArrayList() 
  • you can add items to list:
    • users.add(anohterUser) or
    • users += anotherUser (under the hood it’s users.add(anohterUser) )

      Mutable variable with immutable list:

    var users: List = listOf( User("Tom", 32), User("John", 64) ) 
    • NOTE: you can add* items to list:
      • users += anotherUser — *it creates new ArrayList and assigns it to users

        Mutable variable with mutable list:

      var users: MutableList = mutableListOf( User("Tom", 32), User("John", 64) ) 
      var users = emptyList().toMutableList() //or var users = ArrayList() 
      • NOTE: you can add items to list:
        • users.add(anohterUser)
        • but not using users += anotherUser

        Error: Kotlin: Assignment operators ambiguity:
        public operator fun Collection.plus(element: String): List defined in kotlin.collections
        @InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections

        Источник

        Declaring List of multiple types in Kotlin

        You can create a list that has the first common supertype of your two types as its type parameter, which in this case is Any :

        val myList = mutableListOf() myList.add("string") myList.add(MyObject(null, null)) 

        Of course this way you’ll «lose» the type of the items that are in the list, and every time you get a list item you’ll only know it by the type Any :

        At this point you can make type checks to see what the type of the item is:

        In this specific case where the types are known and limited to two elements, I would use Pair:

        var myList = mutableListOf>() 
        import java.util.Date data class MyObject(val date: Date?, val description: String?) var myList = mutableListOf>() fun main(args: Array)

        Yes and no, that will be list of Any which is super type of every type, You can not create list of MyObject, String

        import java.util.* data class MyObject(val date: Date?, val description: String?) fun main(args: Array)

        Below code is not possible,

        var myList = mutableListOf() 

        Instead you can use sealed class feature available in kotlin. As,

        sealed class MyNewClass < data class MyObject(val date: Date?, val description: String?): MyNewClass() data class ClassForStringData(val data: String): MyNewClass() >// List initialization val newList: List = listOf( MyNewClass.MyObject(Date(), "Description"), MyNewClass.MyObject(Date(), "Description"), MyNewClass.ClassForStringData("New Text"), MyNewClass.ClassForStringData("New another Text") ) //Access fun accessListData()

        With sealed classes you can create a supertype whenever the child classes are known before. Hope this helpful for anyone with similar scenario.

        Источник

        Getting Class of list with generic eg: List::class

        I have a generically typed class Builder that takes a constructor argument Class so I can keep the type around. This is a class that I use a lot in java code so I don’t want to change the signature. When I try to use the constructor like this: Builder>(List::class) I get an error: «Only classes are allowed on the left hand side of a class literal» Any way to resolve this? I can’t change the constructor for Builder , too many java classes rely upon it. I understand the whole type erasure issue, I really just want to make the compiler happy.

        2 Answers 2

        Due to generic type erasure List class has a single implementation for all its generic instantiations. You can only get a class corresponding to List type, and thus create only Builder .

        That builder instance is suitable for building a list of something. And again due to type erasure what that something is you can decide by yourself with the help of unchecked casts:

        Builder(List::class.java) as Builder> Builder(List::class.java as Class>) 

        Another approach is to create inline reified helper function:

        inline fun Builder() = Builder(T::class.java) 

        and use it the following way:

        This won’t retain actual type parameters: T::class.java will represent List , not List , but there’s a solution that will do it for reified generics — super class tokens.

        @hotkey I assume Builder class doesn’t require actual type parameters to be retained, because it takes a constructor argument Class and not Type as it’s stated in the question.

        The solution is to use reified generics in couple with super class tokens.

        Please refer to this question for the method explained. Constructors in Kotlin don’t support reified generics, but you can use TypeReference described there to write a builder factory function which will retain actual generic parameters at runtime:

        inline fun builder(): Builder < val type = object : TypeReference() <>.type return Builder(type) > 

        Then inside Builder you can check if type is ParameterizedType , and if it is, type.actualTypeArguments will contain the actual generic parameters.

        For example, builder>() will retain the information about Number at runtime.

        The limitation of this approach is that you cannot use non-reified generic as a reified type parameter because the type must be known at compile-time.

        Источник

        List

        A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

        Parameters

        E — the type of elements contained in the list. The list is covariant in its element type.

        Properties

        size

        Returns the size of the collection.

        Functions

        contains

        Checks if the specified element is contained in this collection.

        containsAll

        Checks if all elements in the specified collection are contained in this collection.

        get

        Returns the element at the specified index in the list.

        indexOf

        Returns the index of the first occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.

        isEmpty

        Returns true if the collection is empty (contains no elements), false otherwise.

        iterator

        Returns an iterator over the elements of this object.

        lastIndexOf

        Returns the index of the last occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.

        listIterator

        Returns a list iterator over the elements in this list (in proper sequence).

        Returns a list iterator over the elements in this list (in proper sequence), starting at the specified index.

        subList

        Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

        Extension Properties

        indices

        Returns an IntRange of the valid indices for this collection.

        lastIndex

        Returns the index of the last item in the list or -1 if the list is empty.

        Extension Functions

        all

        Returns true if all elements match the given predicate.

        any

        Returns true if collection has at least one element.

        Returns true if at least one element matches the given predicate.

        asIterable

        Returns this collection as an Iterable.

        asReversed

        Returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.

        asSequence

        Creates a Sequence instance that wraps the original collection returning its elements when being iterated.

        associate

        Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

        associateBy

        Returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.

        Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

        associateByTo

        Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.

        Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given collection.

        fun < T , K , V , M : MutableMap < in K , in V >> Iterable < T >. associateByTo (
        destination : M ,
        keySelector : ( T ) -> K ,
        valueTransform : ( T ) -> V
        ) : M

        associateTo

        Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given collection.

        associateWith

        Returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.

        associateWithTo

        Populates and returns the destination mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the valueSelector function applied to that key.

        binarySearch

        Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements, otherwise the result is undefined.

        fun < T : Comparable < T >> List < T ? >. binarySearch (
        element : T ? ,
        fromIndex : Int = 0 ,
        toIndex : Int = size
        ) : Int

        Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the specified comparator, otherwise the result is undefined.

        fun < T > List < T >. binarySearch (
        element : T ,
        comparator : Comparator < in T >,
        fromIndex : Int = 0 ,
        toIndex : Int = size
        ) : Int

        Searches this list or its range for an element for which the given comparison function returns zero using the binary search algorithm.

        fun < T > List < T >. binarySearch (
        fromIndex : Int = 0 ,
        toIndex : Int = size ,
        comparison : ( T ) -> Int
        ) : Int

        Источник

        Читайте также:  Javascript map for objects
Оцените статью