val x = 3.14159265
val s = String.format("%.2f", x);
In the Kotlin playground, test this alternative version that is similar to Python:val x = 3.14159265 val s = "%.2f".format(x);
fun Double.dollar( ) : String {
return "$%.2f".format(this)
}
fun main( ) {
var amount = 15.9576
println(amount.dollar( ))
}
var stateValue = remember { mutableStateOf("abc") }
...
// Usage
val s = stateString.value // <-- Getter
stateString.value = "xyz" // <-- Setter
Try out these alternative formulations:
// Alternative version 1:
var stateValue by remember { mutableStateOf("abc") }
...
// Usage
val s = stateString // <-- Getter
stateString = "xyz" // <-- Setter
// Alternative version 2:
val (value, setValue) = remember { mutableStateOf("abc") }
...
// Usage
val s = value // <-- Getter
setValue("xyz") // <-- Setter
Alternative version 1 seems to be the most popular.
// GroceryItem Class
class GroceryItem(var description : String, var code : Int,
var price : Double, var onSale : Boolean) {
fun salePrice(discount : Double) : Double {
return price * (100 - discount) / 100
}
}
fun main( ) {
// For the GroceryItem objects, since the methods
// equals, hashCode, and toString are not overridden,
// the methods are called directly from the Any class.
// Create four GroceryItem objects.
var gItem1 = GroceryItem("Cabbage", 45678, 1.29, false)
var gItem2 = GroceryItem("Green Beans", 98765, 2.45, true)
var gItem3 = GroceryItem("Cabbage", 45678, 1.29, false)
var gItem4 = gItem2;
// Test Any equals method.
println("${gItem1.equals(gItem2)}")
println("${gItem1.equals(gItem3)}")
println("${gItem2.equals(gItem4)}")
println( )
// Test Any hashCode method.
println("${gItem1.hashCode( )}")
println("${gItem2.hashCode( )}")
println("${gItem3.hashCode( )}")
println("${gItem4.hashCode( )}")
println( )
// Test Any toString method.
println("$gItem1")
println("$gItem2")
println("$gItem3")
println("$gItem4")
}
data GroceryItem(var description : String, var code : Int,
var price : Double, var onSale : Boolean) { }
// Read the entire file into a string:
val s = inputStream.bufferedReader().use {
it.readText( )
}
// Read the file line by line:
var s = ""
inputStream.bufferedReader( ).useLines {
lines -> lines.forEach {
line -> s += line + "\n"
}
}