Hi, is there a way to declare/force a platform typ...
# general-advice
e
Hi, is there a way to declare/force a platform type (
String!
) from Kotlin, with an annotation or similar? I'm making a regex helper where the result gets destructured, and i want the declared types specified for the named groups to decide nullability. for example:
Copy code
regex.match(string, "group", "nullable") { (groupString, nullableString: String?) -> ... }
Where
groupString
would be
String!
and
nullableString
would be
String?
, and an NPE would be thrown if
groupString
ends up being nullable when used. Right now, the only way I've managed to do this is by creating a helper function in java that returns the passed parameter without any nullability info. I would rather not rely on this method if there is a better way to do it, or is it not possible in pure Kotlin?
c
AFAIK it's not possible without having a Java method.
y
@CLOVIS never underestimate the Kotlin type system...
Copy code
import java.util.Scanner

fun main() {
    val regex = "foo".toRegex()
    val string = "fooBar"
    regex.match(string, "group", "nullable") { groupString, nullableString: String? ->
        val foo: String = groupString // works just fine
        if (groupString == null) println("null") // no warnings!
        groupString!! // no warnings!
    }
}

fun Regex.realMatch(string: String, group1: String, group2: String, block: (String?, String?) -> Unit) {}

val flexibleString = typeFromCall { Scanner(System.`in`).nextLine() }
val matchType = function4<String, String, String, _, Unit>(d = function2<_, _, Unit>(flexibleString, flexibleString))
val Regex.match get() = matchType.hint { string, group1, group2, block ->
    realMatch(string, group1, group2, block)
}

sealed class TypeWrapper<T> { fun hint(t: T): T = t }

private object TypeWrapperImpl: TypeWrapper<Nothing>()
@Suppress("UNCHECKED_CAST")
fun <T> type(): TypeWrapper<T> = TypeWrapperImpl as TypeWrapper<T>

inline fun <T> typeFromCall(block: () -> T): TypeWrapper<T> = type()

fun <A, B, R> function2(
    a: TypeWrapper<A> = type(),
    b: TypeWrapper<B> = type(),
    r: TypeWrapper<R> = type(),
): TypeWrapper<(A, B) -> R> = type()
fun <A, B, C, D, R> function4(
    a: TypeWrapper<A> = type(),
    b: TypeWrapper<B> = type(),
    c: TypeWrapper<C> = type(),
    d: TypeWrapper<D> = type(),
    r: TypeWrapper<R> = type(),
): TypeWrapper<(A, B, C, D) -> R> = type()
The trick is simple: we use
TypeWrapper
to have an object to pass around where we want a type This gives us a way to reference "unmentionable" (Voldemort) types. So then it's as simple as finding a suitable function that returns this platform type (I used
nextLine
in this case), and using
typeFromCall
to get that reference Then the annoying part is reconstructing a function type using `TypeWrapper`s. I made my life a little bit easier using default parameters and partially-specifying type arguments using
_
c
Ahah great demo
I'm not sure I'd use that in real code though