Could someone explain to my why this does not work...
# getting-started
g
Could someone explain to my why this does not work?
Copy code
class Test<T : Comparable<T?>>(
    val value: T
)

val a = Test<String?>("Hello")
val b = Test<String>("Hello")

//Neither of the above works
I want to create a class that can both handle
String
and
String?
as the type argument. And if I understand correct,
String
is a sub type of
String?
. If I instead make it non-nullable:
Copy code
class Test<T : Comparable<T>>(
    val value: T
)

val a = Test<String?>("Hello")
val b = Test<String>("Hello")

//Now b works atleast, but not a.
j
String
is not a
Comparable<String?>
and
String?
is not comparable at all
g
But if I do:
Copy code
val test: String? = null
val a = test == "hello"
The
==
operator seems to be the
equals
method in
public class String : Comparable<String>, CharSequence
a
Do you want to make
T
nullable, or the value? For example:
Copy code
class Test<T : Comparable<T>>(
  val value: T?
)

val a = Test<String>("Hello")
val b = Test<String>(null)
g
I want to make
T
nullable, so
Test<String?>
should work as well as
Test<String>
a
can you say more about why you want that? It's not clear to me what that would help with :)
g
It's a long story... I'll try to make it short. I'm wrapping exposed columns in own made wrapper. So I need to be able to support
ExpressionWithColumnType<T>
as well as
ExpressionWithColumnType<T?>
.
For example:
Copy code
object MyTable : LongIdTable(name = "MyTable") {
    val nonNullable = varchar("nonNullable", 255)
    val nullable = varchar("nullable", 255).nullable()
}

class Test<T : Comparable<T?>>(
    expr: ExpressionWithColumnType<T>
)

val a = Test(MyTable.nonNullable)
val b = Test(MyTable.nullable)
Ah, I see. I looked on how exposed did it and they had two type parameters. Like so:
Copy code
object MyTable : LongIdTable(name = "MyTable") {
    val nonNullable = varchar("nonNullable", 255)
    val nullable = varchar("nullable", 255).nullable()
}

class Test<T : Comparable<T>, S : T?>(
    expr: ExpressionWithColumnType<in S>
)

val a = Test(MyTable.nonNullable)
val b = Test(MyTable.nullable)