Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax for Class< ? extends class_name> in kotlin?

Tags:

class

kotlin

I am trying to make an Arraylist that accepts any class variable that inherited from Word_Class but it doesn't work :

var lst = ArrayList<Class<Word_Class>>();
lst.add(Class<Noun_Class>);

I am looking for the syntax for Class< ? extends class_name> in kotlin  

like image 580
user8459720 Avatar asked Aug 14 '17 01:08

user8459720


People also ask

How do you extend a class in Kotlin?

In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).

Can we extend class in Kotlin?

Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

How do I extend my activity on Kotlin?

open class Activity() { ... } fun Activity. requestPermission(permission: String, requestCode: Int) { ActivityCompat. requestPermissions(this, arrayOf(permission), requestCode) } class MyActivity: Activity() { override fun onCreate(savedInstanceState: Bundle?) { super. onCreate(savedInstanceState) ...

How do you extend parent class in Kotlin?

In Kotlin, all classes are final by default. To permit the derived class to inherit from the base class, we must use the open keyword in front of the base class. Kotlin Inheriting property and methods from base class: When we inherit a class then all the properties and functions are also inherited.


1 Answers

You can use the out type projection in Kotlin. it is equivalent to ? extends T in Java, for example:

//                         v--- out type projection
var lst = ArrayList<Class<out Word_Class>>()

To get a Java class you should use KClass#java, for example:

//                 v--- get a KClass instance
lst.add(Noun_Class::class.java)
//                         ^--- get java.lang.Class instance 
like image 86
holi-java Avatar answered Oct 16 '22 14:10

holi-java