Skip to content
This repository has been archived by the owner on Apr 15, 2024. It is now read-only.

Float(string) and similar functions need a better translation #25

Open
vinivendra opened this issue Apr 29, 2020 · 2 comments
Open

Float(string) and similar functions need a better translation #25

vinivendra opened this issue Apr 29, 2020 · 2 comments
Labels
bug Something isn't working gryphon library Affects the Gryphon Swift or Kotlin libraries no solution yet It is not yet clear how to solve this issue

Comments

@vinivendra
Copy link
Owner

The current translation of Float(string) turns it into string.toFloat(). This can be a problem when the translations fail: the Swift version returns nil and the Kotlin version throws an error.

This problem seems to be similar to that in #2.

A way to solve both these problems (and possibly more to come) is to add something like this to the GryphonKotlinLibrary:

fun <T> tryOrNull(autoclosure: () -> T): T? {
	try {
		return autoclosure()
	}
	catch (exception: Exception) {
		return null
	}
}

fun <T> T.nullIf(value: T): T? {
	if (this == value) {
		return null
	}
	else {
		return this
	}
}

fun main(args: Array<String>) {
	val a: Float? = tryOrNull { "abc".toFloat() } // null
	val b: Float? = tryOrNull { "0".toFloat() } // 0.0f

	val c: Int? = (-1).nullIf(-1) // null
	val d: Int? = (3).nullIf(-1) // 3
}

It might seem unintuitive to users at first, but it might be better than creating several individual functions to fix each of these problems.

@vinivendra vinivendra added bug Something isn't working gryphon library Affects the Gryphon Swift or Kotlin libraries no solution yet It is not yet clear how to solve this issue labels Apr 29, 2020
@vinivendra
Copy link
Owner Author

Once this is done, it might be interesting to add a direct translation for Float(string)! etc.

@rlinoz
Copy link

rlinoz commented Jun 18, 2020

Kotlin has a string.toFloatOrNull()

One approach could be to always use the to<NumberType>OrNull() function instead

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working gryphon library Affects the Gryphon Swift or Kotlin libraries no solution yet It is not yet clear how to solve this issue
Projects
None yet
Development

No branches or pull requests

2 participants