I am starting to work in Kotlin and I need to parse a hex String to a long, which in java can be done with
Long.parseLong("ED05265A", 16);
I can not find anything this in Kotlin, although I can find
val i = "2".toLong()
This is not what I am looking for!
before I write anything from scratch is there a built in function for this?
Since Kotlin v1.1 you can use:
"ED05265A".toLong(radix = 16)
Until then use the Java's Long.parseLong.
You can simply use
java.lang.Long.parseLong("ED05265A", 16)
Or
import java.lang.Long.parseLong
[...]
parseLong("ED05265A", 16)
Kotlin is compatible with Java, and you can, and should, use Java's built-in classes and methods.
Related
The documentation is not clear about how to use the merge operation while using rocksdb-jni, and I am not familiar with C++ API, how could I define an merge operator?
You can't define new merge operators in java. They need to be implemented in C++ and then compiled and brought in Java
Eg how to use the built in uint64add operator val options = Options().setMergeOperator(UInt64AddOperator())
and then you can use rocksDB.merge(keyByteArray, longValueByteArray)
In Kotlin (1.0.6), through reflection I need to iterate over the members of a class (let's call it Foo), and do something based on the return type. I can write the following, which works:
Foo::class.members{ m ->
if(Integer.TYPE.isAssignableFrom(m.returnType.javaType as Class<*>)){
//do something here
} else if ...
}
the problem is that the if statement (to handle kotlin.Int) is quite ugly. Is there any better way in Kotlin to achieve the same result without having to rely directly on the Java API?
No, there is not a better way pre-1.1 Kotlin.
You can use Int::class.javaObjectType instead of Integer.TYPE to avoid using java.lang.Integer in Kotlin code but that makes the statement even longer (although more idiomatic).
In Kotlin 1.1 you can use isSubtypeOf or query jvmErasure.allSupertypes directly.
What's the standard way to work with dates and times in Scala? Should I use Java types such as java.util.Date or there are native Scala alternatives?
From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310). There are efforts on creating scala libraries wrapping java.time for scala such as scala-time. If targeting lower than SE 8 use one of the below. Also see Why JSR-310 isn't Joda-Time
Awesome scala lists many of the popular Scala DateTime apis
A new Scala wrapper for Joda Time. This project forked from scala-time since it seems that scala-time is no longer maintained.
import com.github.nscala_time.time.Imports._
DateTime.now // returns org.joda.time.DateTime = 2009-04-27T13:25:42.659-07:00
DateTime.now.hour(2).minute(45).second(10) // returns org.joda.time.DateTime = 2009-04-27T02:45:10.313-07:00
DateTime.now + 2.months // returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00
DateTime.nextMonth < DateTime.now + 2.months // returns Boolean = true
DateTime.now to DateTime.tomorrow // return org.joda.time.Interval = > 2009-04-27T13:47:14.840/2009-04-28T13:47:14.840
(DateTime.now to DateTime.nextSecond).millis // returns Long = 1000
2.hours + 45.minutes + 10.seconds
// returns com.github.nscala_time.time.DurationBuilder
// (can be used as a Duration or as a Period)
(2.hours + 45.minutes + 10.seconds).millis
// returns Long = 9910000
2.months + 3.days
// returns Period
Joda Time is a good Java library, there is a Scala wrapper / implicit conversion library avaliable for Joda Time at scala-time created by Jorge Ortiz. (Note implicits have a performance hit, but it depends on what you do if you will notice. And if you run into a performance problem you can just revert to the Joda interface)
From the README:
USAGE:
import org.scala_tools.time.Imports._
DateTime.now
// returns org.joda.time.DateTime = 2009-04-27T13:25:42.659-07:00
DateTime.now.hour(2).minute(45).second(10)
// returns org.joda.time.DateTime = 2009-04-27T02:45:10.313-07:00
DateTime.now + 2.months
// returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00
DateTime.nextMonth < DateTime.now + 2.months
// returns Boolean = true
DateTime.now to DateTime.tomorrow
// return org.joda.time.Interval =
// 2009-04-27T13:47:14.840/2009-04-28T13:47:14.840
(DateTime.now to DateTime.nextSecond).millis
// returns Long = 1000
2.hours + 45.minutes + 10.seconds
// returns org.scala_tools.time.DurationBuilder
// (can be used as a Duration or as a Period)
(2.hours + 45.minutes + 10.seconds).millis
// returns Long = 9910000
2.months + 3.days
// returns Period
If you are using Java 8, then there is no need to use nscala anymore. The Joda-Time library has been moved into Java 8 under the java.time package (JSR-310). Just import that package into your Scala project.
There is no standard way to work with dates in Scala. The options available are:
Use java.time (if you are using Java 8) since it has the best of JODA time built into it. No implicits.
Use nscala-time.
Lamma date library (relatively new library on the scene)
I would avoid using java.util.Date due to the well-documented issues surrounding it.
MOTIVATION:
The Java Date and Calendar libraries are largely inadequate. They are mutable,
not thread-safe, and very inconvenient to use.
The Joda Time library is a great replacement for Java's Date and Calendar
classes. They're immutable by default, have a much richer and nicer API, and
can easily be converted to Java's Date and Calendar classes when necessary.
This project provides a thin layer of convenience around the Joda Time
libraries, making them more idiomatic to use within Scala.
(copied from https://github.com/jorgeortiz85/scala-time)
Everyone uses JodaTime, these Scala helper/wrapper libraries may need re-compilation with new versions of Scala. Jodatime is the only time library that's been around for a long time, and is stable and works reliably with every version of Scala.
Does anyone know the status of a fully-featured reflection API for Scala?
I know that you can use Java's reflection API to do simple things but this does not work well with Scala's language features. I found an interesting article describing an experimental Scala Mirroring API but as far as I know this is still experimental. I've also found mention of a ScalaSigParser but this seems to be pretty low level.
This is more of a curiosity than anything else as I am currently just playing around with Scala. I thought that the answer to this question might also be useful to others interested in Scala.
The "immutable replacement for the JavaBean style pattern" can be expressed named parameters and optionally the #BeanProperty annotation:
import reflect._
case class A(#BeanProperty val x: String, #BeanProperty val y : Int)
A(x = "s", y = 3)
A(y = 3, x = "s")
Adding methods (more precise: defining a new interface) makes only sense in a statically typed language if the client knowns about the new methods and can compile against the interface. With structural typing clients can define methods they expect to be present in an object. The Scala compiler will transform the structural type into reflection code which may fail at runtime.
type T = {def go(x : Int): Int }
def y(any : Any) = any.asInstanceOf[T].go(2)
class A{
def go(x : Int) = x + 1
}
y(new A())
y(new {}) //this will fail
You can define new classes or traits with the interpreter on the fly. The Interpret method transforms Scala code to byte code.
You've already mentioned the ScalaSigParser which is not exactly easy to work with.
I think the rest of features you like are not there yet.
Is their an equivalent to C#'s Expression API in scala?
For example, I would like to have a lambda like this:
(Foo) => Foo.bar
and be able to access "bar" in the function it is passed to.
This is not supported by Scala. ScalaQL: Language-Integrated Database Queries
for Scala describes a LINQ-like functionality in Scala:
While it is possible for Microsoft to
simply extend their language with this
particular feature, lowly application
developers are not so fortunate. For
exam- ple, there is no way for anyone
(outside of Sun Microsystems) to
implement any form of LINQ within Java
because of the language modications
which would be required. We faced a
similar problem attempting to
implement LINQ in Scala.
Fortunately, Scala is actually
powerful enough in and of itself to
implement a form of LINQ even without
adding support for expression trees.
Through a combination of operator
overloading, implicit conversions, and
controlled call- by-name semantics, we
have been able to achieve the same
eect without making any changes to
the language itself.
There is an experimental scala.reflect.Code.lift which might be of interest, but the short answer is no, Scala does not have access to the AST in any form (expression trees are a subset of C#'s AST).
It's not quite clear to me what you want. If you want a function that returns a getter for a field, you can do that quite easily:
class Holder(var s: String) { }
class StringSaver(f: Holder => (() => String), h: Holder) {
val getter = f(h)
def lookAtString = getter()
}
val held = new Holder("Hello")
val ss = new StringSaver((h: Holder) => (h.s _) , held)
println(ss.lookAtString)
held.s = "Bye now"
println(ss.lookAtString)
The key is to turn the getter h.s into a function via (h.s _).
No, to the best of my knowledge.