https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

rtsketo

06/09/2021, 12:56 PM
Is there anyway in Kotlin to have two constructors in class with both having lists as an argument but with different types in them? For example:
Copy code
constructor(aList : List<A>)  /* Main constructor */
constructor(bList : List<B>) : this (bList.toListA())
I get the following:
Copy code
Platform declaration clash: The following declarations have the same JVM signature ((Ljava/util/List;)V):
How do I distinguish between them?
m

mkrussel

06/09/2021, 1:03 PM
I don't think you can with constructors. Instead you probably need to create factory methods and use the JvmName annotation to make the name different for Java callers. You can use the name of the class for the factory methods if you want it to look like a constructor. Probably keep the List<A> one as a constructor and make the List<B> a function.
👍🏼 1
r

rtsketo

06/09/2021, 1:07 PM
Thanks! Came to the same conclusion just a minute ago. You can even make the function look as a constructor by overriding the
invoke
operator. Still... it kind of feels like a hack to me. Pretty weird Kotlin doesn't offer a better solution.
c

CLOVIS

06/09/2021, 1:13 PM
To my knowledge, it is considered bad practice to use Companion.invoke to mimic a constructor. The better practice is to have a top-level function that has the same name as the class (with the capitals and everything).
1
(for example the
List
factory in the standard library)
Also for the ‘lack of better solution', Project Valhalla will bring runtime reified generics to the JVM, maybe then?
e

ephemient

06/09/2021, 2:41 PM
as far as I'm aware, there is still no spec for generic specialization. Valhalla has implemented L-world types but not https://openjdk.java.net/jeps/218
d

Dominaezzz

06/09/2021, 4:17 PM
I'd love top level functions more if intellij didn't remove the class icon from the Kotlin file.
2
y

y9san9

06/09/2021, 4:38 PM
Haha, felt something same at the beginning of my Kotlin programming :) Now this problem in my mind fixed and it's not problem. Additionally the idea now does not provide a
function name
warning in case if such functions have the same return type as its name.
c

CLOVIS

06/09/2021, 7:37 PM
@Dominaezzz then you can put it in the companion object and
import static
it. Honestly though, you shouldn't architecture your code just so you have a specific icon on your screen, especially when that stops you from using one of the most important features of the language
💯 1
r

rtsketo

06/09/2021, 7:54 PM
OCD, gift and curse at the same time.
☝🏼 1
1