Few Questions Related to Generics


#1

Hi,

First question is related to instantiating vars of generic type:

  class A<T> {
          // if T’s upper bound is ‘Any?’, why is this illegal:
          var t : T = null

          // this compiles, but with a warning: “‘T’ has a nullable upper bound…”
          var t : T? = null
  }

BTW, what I actually want there is

  var t: T = default(T)

but I don’t know how to do that in Kotlin.

Second question is about method overloading. Not terribly important, but I’m curious. I’d like to know if you’re planning to add support for this.

If I have a method like this one:

  fun abc (a:String) : Any? {…}

Why can’t I have a generic version with same name:

  fun abc<T> (a: String) : T {…}

Thank you for your time :slight_smile:


#2

  class A<T> {           // if T's upper bound is 'Any?', why is this illegal:           var t : T = null

Because it's only an _upper_ bound, i.e. T may be String, and assgning a null to String (not String?) is not allowed.

          // this compiles, but with a warning: "'T' has a nullable upper bound..."           var t : T? = null

T may be Foo?, and in that case T? is Foo? as well, so when you see null, you have no way to tell whether it comes as a value of T or as value of T?

BTW, what I actually want there is

  var t: T = default(T)

What is “default(some non-null type)”? For example, “default(PrintStream)”? We could agree on defaults for things like Int or String or Foo?, but not for an arbitrary non-null type.

Second question is about method overloading. Not terribly important, but I'm curious. I'd like to know if you're planning to add support for this.

If I have a method like this one:

  fun abc (a:String) : Any? {…}

Why can’t I have a generic version with same name:

  fun abc<T> (a: String) : T {…}

Because of how JVM works: generics are erased and effective binary signatures of the two methods above are the same, which is not allowed.


#3

Thank you, Andrey.

This is my 3rd or 4th attempt at replying :slight_smile: As I was trying to reply with more questions, I became more and more aware of how little I know, and how stupid those questions would be. Now I only have one simple question :slight_smile: How do I make sure T is a nullable type?


#4

Currently there's no way to make sure thet a type variable will definitely hold a nullable type. What you can do is make sure it holds a non-null type, and then use T? to make sure the type is nullable:

class C<T: Any> { // T can not be nullable   var x: T? = null // no warning here

}