From 05615dd48bd9f0c83c40ee8596cbce9bb29ab0d6 Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Thu, 22 Oct 2015 22:59:38 +0300 Subject: [PATCH] Introduce String.toByte() #KT-8833 Fixed --- libraries/stdlib/src/kotlin/text/StringsJVM.kt | 6 ++++++ libraries/stdlib/test/text/StringJVMTest.kt | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/libraries/stdlib/src/kotlin/text/StringsJVM.kt b/libraries/stdlib/src/kotlin/text/StringsJVM.kt index 575445ff693..817446f91d8 100644 --- a/libraries/stdlib/src/kotlin/text/StringsJVM.kt +++ b/libraries/stdlib/src/kotlin/text/StringsJVM.kt @@ -333,6 +333,12 @@ public fun String.toUpperCase(locale: java.util.Locale): String = (this as java. */ public fun String.toBoolean(): Boolean = java.lang.Boolean.parseBoolean(this) +/** + * Parses the string as a signed [Byte] number and returns the result. + * @throws NumberFormatException if the string is not a valid representation of a number. + */ +public fun String.toByte(): Byte = java.lang.Byte.parseByte(this) + /** * Parses the string as a [Short] number and returns the result. * @throws NumberFormatException if the string is not a valid representation of a number. diff --git a/libraries/stdlib/test/text/StringJVMTest.kt b/libraries/stdlib/test/text/StringJVMTest.kt index 9da73458a57..d3ea5381709 100644 --- a/libraries/stdlib/test/text/StringJVMTest.kt +++ b/libraries/stdlib/test/text/StringJVMTest.kt @@ -27,6 +27,18 @@ class StringJVMTest { assertEquals("", ns.orEmpty()) } + @test fun toBoolean() { + assertEquals(true, "true".toBoolean()) + assertEquals(true, "True".toBoolean()) + assertEquals(false, "false".toBoolean()) + assertEquals(false, "not so true".toBoolean()) + } + + @test fun toByte() { + assertEquals(77.toByte(), "77".toByte()) + assertFails { "255".toByte() } + } + @test fun toShort() { assertEquals(77.toShort(), "77".toShort()) }